源程序:
#include <stdio.h>
#define MAXSIZE 50
typedef struct
{
int data[MAXSIZE];
int top;
}Sqstack;
int Push(Sqstack *S, int x) //进栈
{
if (S->top == MAXSIZE - 1)
{
printf("栈已满!\n");
printf("\n");
return 0;
}
// S->top++; //指针上移,然后赋值
S->data[++S->top] = x;
printf("进栈成功!\n");
printf("\n");
return 1;
}
int Pop(Sqstack *S, int x) //出栈
{
if (S->top == -1)
{
printf("栈已空!\n");
printf("\n");
return 0;
}
x = S->data[S->top--]; //取出元素,指针下移
//S->top--;
printf("栈顶元素出栈成功!\n");
printf("\n");
return 1;
}
int Display(Sqstack *S)
{
if (S->top == -1)
{
printf("栈已空!\n");
printf("\n");
return 0;
}
int top = S->top;
while (top != -1)
{
printf("%d\n", S->data[top--]);
//top--;
}
printf("\n");
}
int main()
{
Sqstack *S;
S->top = -1;
int mark = 1;
int x, y;
while (mark == 1)
{
int temp;
printf("按1进栈,按2出栈,按3显示栈,按0退出!\n");
scanf(" %d", &temp);
switch (temp)
{
case 1:
printf("\n");
scanf(" %d", &x);
Push(S, x);
break;
case 2:
printf("\n");
Pop(S,y);
break;
case 3:
printf("\n");
Display(S);
break;
case 0:
printf("\n");
mark = 0;
break;
}
}
}
演示截图: