#include<stdio.h>
#include<stdlib.h>
#define Max 50//栈中存放的最大元素个数
typedef struct
{
int elem[Max];//用来存放栈中元素的一维数组
int top;//用来存放栈顶元素的下标,top为-1时,表示空栈
}Seqstack;
int initStack(Seqstack *S);//栈的初始化
int push(Seqstack *S);//进栈
void Pop(Seqstack *S);//出栈
int main(void)
{
Seqstack S;
int b;//接收函数返回值
int a;//接收菜单输入值
while (1)
{
printf("*********************\n");
printf("1.InitStack\n");
printf("2.Push\n");
printf("3.Pop\n");
printf("4.Exit\n");
printf("*********************\n");
printf("Please input the number of the menu:\n");
scanf("%d", &a);
switch (a)
{
case 1:b=initStack(&S);
if (b == 1)
{
printf("InitStack Success!\n");
}
else
{
printf("Inint Fail\n");
}
break;
case 2:b = push(&S);
if (b == 0)
{
printf("Push Fail!\n");
}
if (b == 1)
{
printf("Push Success!\n");
}
break;
case 3:Pop(&S);
break;
case 4:exit(0);
break;
default:printf("You input the figure is error\n");
printf("Please input the figure again:\n");
break;
}
}
getchar();
getchar();
return 0;
}
int initStack(Seqstack *S)//栈的初始化
{
S->top = -1;//构建一个空栈,第一次先将位置置为-1
return 1;
}
int push(Seqstack *S)
{
int a;
int flag=1;//标志输入结束
printf("Please input the figure that you want push(end by 0):\n");
while (flag)
{
scanf("%d",&a);
if (a==0)
{
flag = 0;
continue;
}
if (S->top == Max - 1)//栈已满
{
return 0;
}
S->top++;//位置上移
S->elem[S->top] = a;//将元素放在栈中
}
return 1;
}
void Pop(Seqstack *S)
{
int a;
while (S->top!=-1)//当栈顶不在最下面时继续
{
a = S->elem[S->top];
S->top--;//位置下移
printf("%d\t",a);
}
printf("\n");
}
顺序栈
最新推荐文章于 2023-10-20 21:42:37 发布