- 77
- 0
- 约6.5千字
- 约 9页
- 2015-09-26 发布于重庆
- 举报
栈的基本操作
栈的基本操作
//顺序栈
顺序栈的存储结构和操作的实现 在C语言中,预设一个数组的最大空间,栈底设置在0下标端,栈顶随着插入和删除元素而变化,用一个整型变量top来指示栈顶的位置。
#includestdio.h
#includeconio.h n
#define m 10
typedef struct
{
int a[m];
int top;
}stack;
0
int main(void)
{ 压入(PUSH): S[++top]=an+1弹出( POP) : e=S[top - -]
int isempty(stack *s);
int isfull(stack *s);
int gettop(stack *s,int x); //取最后进栈的元素
int get(stack *s,int b);
void push(stack *s,int x); //进栈
void pop(stack *s); //出栈
int i,x,b,c,j=0; stack *s;
s = (stack *)malloc(sizeof(stack));
s-top = 0;
printf(please input 10 numbers:\n);
for(i=0;im;i++)
{
scanf(%d,x);
push(s,x);
}
// printf(%d\n,s-top);
if(isempty(s))
printf(空栈\n);
else
printf(非空\n);
if(isfull(s))
printf(满栈\n);
else
printf(非满\n);
gettop(s,x);
printf(最后一个进栈的元素为%d\n,x);
printf(请输入要找的第几号元素?\n);
scanf(%d,b);
c=get(s,b);
printf(第%d元素为%d\n,b,c);
printf(是否出栈,出栈请输入非零数:);
scanf(%d,j);
if(j)
{
printf(原栈中元素为:\n);
pop(s);
}
else
printf(出栈失败!\n);
return 0;
}
int isempty(stack *s)
{
if(s-top==0)
return 1;
return 0;
}
int isfull(stack *s)
{
if(s-top==m)
return 1;
else
return 0;
}
int gettop(stack *s,int x) //得到栈的最后一个元素
{
int i;
i = isempty(s);
if(i)
printf(empty);
else
x=s-a[s-top-1];
return x;
}void push(stack *s,int x) //进栈{
int i;
i = isfull(s);
if(i)
printf(overflow);
else
{
s-a[s-top] = x;
s-top++;
}
}
int get(stack *s,int b) //得到栈的第B个元素
{
int c;
c=s-a[b-1];
return c;
}void pop(stack *s) //出栈
{
int i,j,t;
t = s-top;
for(i = 0; it-1; i++)
{
printf(%d ,s-a[s-top-1]);
s-top--;
}
printf(%d\n,s-a[s-top-1]);
s-top--;
j = isempty(s);
if(j)
printf(出栈成功!\n);
}
//栈的链式存储结构
栈的链式存储结构与线性表的链式存储结构相同,是通过由结点构成的单链表实现的。
为操作方便我们使用无头结点的单链表。此时栈顶为单链表的第一个结点,整个单链表为一个链栈。
#includestdio.h
#includestdlib.h
#define datatype int
//1.链栈的类型定义
typedef struct node
{
datatype data; /*数据域*/
struct node *next; /*指针域*/
}li
原创力文档

文档评论(0)