#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 1024
typedef int elemtype;
typedef struct SequenStack
{
elemtype data[MAXSIZE];
int top; //设置顺序栈的栈顶指针
}SequenStack; //顺序栈的结构类型
SequenStack * Init_SequenStack();
int SequenStack_Length(SequenStack *S);
int SequenStack_Empty(SequenStack *S);
int SequenStack_Full(SequenStack *S);
int Push_SequenStack(SequenStack *S,elemtype x);
int Pop_SequenStack(SequenStack *S);
void menu();
void menu()
{ system("cls");
printf("\t\t1-initial stack\n");
printf("\t\t2-input data\n");
printf("\t\t3-get length\n");
printf("\t\t4-判断栈空\n");
printf("\t\t5-判断栈满\n");
printf("\t\t6-出栈\n");
printf("\t\t7-输出\n");
printf("\t\t#-quit\n");
printf("Please select: ");
}
int main()
{
char cmd;
SequenStack *S;
elemtype x;
int isdo,i,len;
system("cls");
menu();
while((cmd=getchar())!='#')
{
switch(cmd)
{ case '1': S= Init_SequenStack( );
printf("\nCreatied the stack!\n");
printf("\n\n\n\t\t\t");
break;
case '2': printf("请插入数据 0结束\n");
scanf("%d",&x);
while(x!=0)
{
isdo=Push_SequenStack(S,x);
if(isdo==0)
{ printf("栈满结束\n");
break;
}
scanf("%d",&x);
}
printf("\n\n\n\t\t\t");
break;
case '3': len=SequenStack_Length(S);
printf("\nCaculated the Length of the list...\n");
printf("len=%d\n",len);
printf("\n\n\n\t\t\t");
break;
case '4': isdo=SequenStack_Empty(S);
if(isdo==0)
{
printf("栈不是空\n");
}
else if(isdo==1)
{
printf("栈为空\n");
}
printf("\n\n\n\t\t\t");
break;
case '5': isdo=SequenStack_Full(S);
if(isdo==0)
{
printf("栈不满\n");
}
else if(isdo==1)
{
printf("栈为满\n");
}
printf("\n\n\n\t\t\t");
break;
case '6': printf("\nGeting the top data of the stack...\n");
isdo=Pop_SequenStack(S);
if(isdo==1)
{
len--;
printf("出栈成功\n");
printf("新的栈顶元素:%d\n",S->data[S->top]);
}
else if(isdo==0)
{
printf("出栈失败\n");
}
printf("\n\n\n\t\t\t");
break;
case '7': while(S->top>=0)
{
printf("%d\t",S->data[S->top]);
S->top--;
}
for(i=0;i<len;i++)
{
S->top++;
}
printf("\n\n\n\t\t\t");
break;
}
fflush(stdin);
system("pause");
menu();
}
return 0;
}
SequenStack * Init_SequenStack() //初始化
{
SequenStack *S; //定义顺序栈指针变量
S=(SequenStack *)malloc(sizeof(SequenStack)); //申请内存空间
S->top=-1;
return S;
}
//判断栈空
int SequenStack_Empty(SequenStack *S)
{
if(S->top==-1)
{
return 1;
}
else
{
return 0;
}
}
//判断栈满
int SequenStack_Full(SequenStack *S)
{
if(S->top+1==MAXSIZE)
{
return 1;
}
else
{
return 0;
}
}
//求顺序栈的长度
int SequenStack_Length(SequenStack *S)
{
return S->top+1;
}
//入栈
int Push_SequenStack(SequenStack *S,elemtype x)
{
if(S->top>=MAXSIZE-1)
{
return 0; //栈满,插入失败,返回0;
}
else
{
S->top++;
S->data[S->top]=x;
return 1;
}
}
//出栈
int Pop_SequenStack(SequenStack *S)
{
if(S->top==-1)
{
return 0; //栈空
}
else
{
S->top--;
return 1;
}
}