顺序栈无数组代码如下可直接编译运行无错
//2020.3.24 by大彪不爱嚼米饭粒儿
//Init 初始化
//Push 进栈
//Pop 出栈
//Gettop 取栈顶元素
//Print 输出栈内元素 与出栈区别注意
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define Plus 10
typedef int Status;
typedef struct {
int *top;
int *base;
int size;
}Sqstack;
Status Init(Sqstack *S)
{
S->base = (int *)malloc(MAXSIZE*sizeof(int));
if(!S->base)
{
printf("ERROR");
}
S->top = S->base;
S->size = MAXSIZE;
return 1;
}
Status Push(Sqstack *S,int e)
{
if(S->top-S->base >=S->size)
{
S->base = (int*)realloc(S->base,(S->size+Plus)*sizeof(int));
if(!S->base)printf("ERROR");
S->top = S->base+S->size;
S->size = S->size+Plus;
}
*(S->top)=e; //进栈
S->top++; //栈顶上移
return 1;
}
Status Pop(Sqstack *S,int *e)
{
if(S->base == S->top )
{
exit(-1);
}
S->top--;
*e=*S->top;
return 1;
}
Status Gettop(Sqstack S,int *e)
{
if(S.top == S.base )
{
exit(-1);
}
e = S.top-1;
return 1;
}
Status Print(Sqstack S)
{
while(S.base!=S.top)
{
S.top--;
printf("%d ",*S.top);
}
printf("\n");
}
int main()
{
int n;
int max;
int date;
int i;
Sqstack S;
printf("1,初始化\n2,入栈\n3,出栈\n4,读取栈顶元素\n5,输出栈内元素\n0,退出\n");
scanf("%d",&n);
while(n!=0)
{
switch(n)
{
case 1:
Init(&S);
printf("初始化成功\n");
break;
case 2:
printf("输入栈长度\n");
scanf("%d",&max);
printf("输入栈数据\n");
for(i = 0;i<max;i++)
{
scanf("%d",&date);
Push(&S,date);
}
printf("栈数据输入完毕\n");
break;
case 3:
printf("出栈\n");
for(i=0;i<max;i++)
{
Pop(&S,&date);
printf("%d ",date);
}
printf("\n出栈完成\n");
break;
case 4:
printf("读取栈顶元素\n");
Gettop(S,&date);
printf("%d",date);
printf("\n");break;
case 5:
Print(S);break;
}
scanf("%d",&n);
}
return 0;
}
//error:*(S->top)=e; 第一次写成e= *(S->top) 导致出栈出现问题
顺序栈还是比较简单的,重新攻坚单链表了