顺序栈操作

来源:互联网 发布:网络爬虫用什么语言好 编辑:程序博客网 时间:2024/05/21 08:36

include

include

define StackInitSize 100

typedef int StackElementType;/栈元素的类型设定为整型/
typedef struct{
StackElementType data[StackInitSize];
int top;
}SeqStack;
//栈的初始化
SeqStack *InitStack()
{
SeqStack *s;
s=(SeqStack *)malloc(sizeof(SeqStack));//动态申请栈存储空间
if(s!=NULL)
{//将顺序栈置空
s->top=-1;
return s;
}
else{printf(“没有足够的内存空间,申请失败,程序运行终止\n”);
exit(0);}
}
//判断栈是否为空栈
int IsEmpty(SeqStack *s)
{
return (s->top==-1)?1:0 //栈为空返回1,否则返回0
}
//销毁栈
void DestoryStack (SeqStack *s)
{
free(s);
printf(“栈已销毁\n”);
return;
}
//进栈操作
void push(SeqStack *s,StackElementType x)
{
if(s->top==StackInitSize-1)
{
printf(“栈满,程序终止\n”);
exit(0);
}
else{
s->top++;
s->data[s->top]=x;
}
return ;
}
//退栈操作
StackElementType pop(SeqStack *s)
{
StackElementType temp;
if(IsEmpty(s))
{printf(“栈空,程序终止\n”);exit(0);}
else
{temp=s->data[s->top];
s->top–;
return temp;}
}
//读取栈顶元素
StackElementType GetTop(SeqStack *s)
{
if(IsEmpty(s))
{printf(“空栈,程序终止\n”);
exit(0);}
else return s->data[s->top];
}
void display(SeqStack *s)
{
int p;
for(p=s->top;p>=0;p–)
{printf(“%d->”,s->data[p]);}
printf(“\b\b\n”);
}
void main()
{
int i;
SeqStack *stack; //定义顺序栈stack
stack=Initstack();
for(i=1;i<=10;i++)
{Push(stack,i*i);}
display(stack);
pop(stack);
pop(stack);
Push(stack,999);
printf(“当前栈顶元素=%d\n”,GetTop(stack));
display(stack);
DestoryStack(stack);
}

原创粉丝点击