Code
/*顺序表实现栈的一系列操作*/ #include<stdio.h> #include<stdlib.h> #define Stack_Size 50 //设栈中元素个数为50 #define OK 1 #define ERROR 0 typedef struct { int elem[Stack_Size]; //用来存放栈中元素的一维数组 int top; //用来存放栈顶元素的下标,top为 -1 表示空栈 }SeqStack; /**********************各个子函数的定义*********************/ int initStack(SeqStack *S); //初始化顺序栈 void push(SeqStack *S,int n); //顺序栈进栈运算 void pop(SeqStack *S); //顺序栈出栈运算 int getTop(SeqStack *S,int *s); //读取栈顶元素 int main() { SeqStack *S; int choice; while(true) { printf("*****************Please enter your choice*****************\n\n"); printf(" choice 1:Stack initialization\n"); printf(" choice 2:Into the stack\n"); printf(" choice 3:Out of the stack\n"); printf(" choice 4:Read the stack elements\n"); printf(" choice 0:exit\n\n"); scanf("%d",&choice); switch(choice) { case 1: (initStack(S)==1)?printf("initStck success.\n"):printf("initStack ERROR\n"); break; case 2: int n; printf("Please enter the number into the stack elements:"); scanf("%d",&n); push(S,n); break; case 3: pop(S); break; case 4: int* s; (getTop(S,s)==1)? printf("栈顶元素是:%d.\n",*s):printf("An empty stack error!!!!\n"); //三目运算符 break; case 0: exit(0); break; default: printf("ERROR!!\n"); exit(0); break; } } return 0; } /**********************各个子函数功能的实现*********************/ int initStack(SeqStack *S) //初始化顺序栈 { if(S!=NULL) { S->top=-1; //置为空栈 return OK; } else return ERROR; //内存空间不足 } void push(SeqStack *S,int n) //进栈 ,将元素压入栈中 { int n1,n2; if(((S->top)+n)<=Stack_Size-1) //压入栈中的元素不能超过栈的最大存储 { printf("Please enter into the stack elements in turn:\n"); for(n1=0;n1<n;n1++) { scanf("%d",&n2); S->top++; //移动栈顶指针 S->elem[S->top]=n2; } printf("%d个元素依次进栈成功\n",n); } else { //栈空间不够 printf("ERROR There is insufficient space on the stack.\n"); } } void pop(SeqStack *S) { //栈顶元素出栈 int a; if(S->top==-1) { //栈为空,操作失败 printf("An empty stack error!!!!\n"); } else { a=S->elem[S->top]; S->top--; printf("栈顶元素%d出栈成功.\n",a); //出栈成功 } } int getTop(SeqStack *S,int *s) //获取栈顶元素 { if(S->top==-1) { //栈为空,操作失败 return ERROR; } else { *s=S->elem[S->top]; //读取栈顶元素成功 return OK; } }
转载于:https://www.cnblogs.com/qftm/p/10317155.html