#include <stdio.h>
#include <stdlib.h>
typedef int elemType;
struct stack{
elemType *list;
int top;
int maxsize;
};
void againMalloc(struct stack *s)
{
elemType *p;
p = realloc(s->list, 2*s->maxsize*sizeof(elemType));
if(!p){
printf("内存分配失败,退出程序!");
exit(1);
}
s->list=p;
s->maxsize = 2 * s->maxsize;
return ;
}
void initStack(struct stack *s,int ms)
{
if(ms<=0)
{
printf("ms值非法!");
exit(1);
}
s->list = malloc(ms *sizeof(elemType));
s->maxsize = ms;
s->top = -1;
if(!s->list)
{
printf("空间开辟失败!");
exit(1);
}
}
void push(struct stack *s,elemType x)
{
if(s->top+1 ==s->maxsize)
{
printf("栈满,分配更大的空间!");
againMalloc(s);
}
s->list[s->top+1]=x;
s->top++;
}
elemType pop(struct stack *s)
{
if(s->top== -1)
{
printf("空栈,退出!");
exit(1);
}
s->top--;
return s->list[s->top+1];
}
elemType peek(struct stack *s)
{
if(s->top==-1)
{
printf("空栈,退出!");
exit(1);
}
else
{
return s->list[s->top+1];
}
}
int emptyStack(struct stack *s)
{
if(s->top!=-1)
{
return 1;
}
else
return 0;
}
void clearStack(struct stack *s)
{
if(s->list){
free(s->list);
s->list = NULL;
s->top = -1;
s->maxsize = 0;
return ;
}
}
void traverse(struct stack *s)
{
int i = 0;
printf("从栈顶到依次输出:");
for(i=s->top+1;i!=0;i--)
{
printf("%d ",s->list[i-1 ]);
}
return ;
}
void main()
{
elemType x = 0;
int ms = 0,i = 0;
struct stack s;
while(1)
{
printf("1->扩展顺序栈\n");
printf("2->初始化顺序栈\n");
printf("3->增加顺序栈\n");
printf("4->删除顺序栈\n");
printf("5->判断顺序栈\n");
printf("6->清除顺序栈\n");
printf("x->遍历顺序栈\n");
printf("清选择操作:");
scanf("%d",&i);
switch(i)
{
case 1:
againMalloc(&s);
break;
case 2:
printf("请输入构造顺序栈表大小:");
scanf("%d",&ms);
initStack(&s,ms);
break;
case 3:
printf("请输入入栈元素x:");
scanf("%d",&x);
push(&s,x);
break;
case 4:
printf("出栈元素为%d",pop(&s));
getchar();
getchar();
break;
case 5:
if(emptyStack(&s))
{
printf("栈表非空!");
getchar();
getchar();
break;
}
else
printf("栈表为空!");
getchar();
getchar();
break;
case 6:
clearStack(&s);
printf("栈表销毁成功!");
getchar();
getchar();
break;
default:
traverse(&s);
getchar();
getchar();
break;
}
system("cls");
}
}