voidPrintStack(SqStack S){int i = S.top+1;if(S.top !=-1)// 判空{while(i--)// 遍历顺序栈{printf("%d ", S.data[S.top--]);// 从上到下依次遍历}printf("\n");}else{printf("SqStack is empty!\n");}}
2.7 主函数
intmain(){
SqStack S;InitStack(S);
ElemType e;//创建栈int len;printf("Please enter the length of data you want to insert!(Length < %d)\n", MaxSize);scanf("%d",&len);printf("Please enter %d elements one by one in order!\n", len);while(len--){scanf("%d",&e);Push(S, e);}PrintStack(S);//入栈printf("please input the element you want to input to the stack\n");scanf("%d",&e);Push(S,e);printf("You have done it!\n");PrintStack(S);//出栈printf("please input the element you want to out \n");Pop(S, e);printf("the %d have be POPPED!\n",e);PrintStack(S);//获取栈顶元素printf("the top element is %d",GetTop(S));return0;}
2.完整代码
//顺序栈#include<stdio.h>#defineMaxSize10typedefint ElemType;typedefstruct{
ElemType data[MaxSize];int top;//栈顶指针,记录了数组的下标}SqStack;//初始化voidInitStack(SqStack &S){
S.top =-1;}//进栈boolPush(SqStack &S, ElemType e){if(S.top == MaxSize-1)//栈满的情况{returnfalse;}
S.top = S.top+1;
S.data[S.top]= e;//S.data[++s.top] = e;returntrue;}//出栈boolPop(SqStack &S, ElemType &e){if(S.top == MaxSize-1){returnfalse;}
S.data[S.top]= e;
S.top = S.top-1;//S.data[S.top--] = e;returntrue;}//获取栈顶元素intGetTop(SqStack S){return S.data[S.top];}//输出voidPrintStack(SqStack S){int i = S.top+1;if(S.top !=-1)// 判空{while(i--)// 遍历顺序栈{printf("%d ", S.data[S.top--]);// 从上到下依次遍历}printf("\n");}else{printf("SqStack is empty!\n");}}intmain(){
SqStack S;InitStack(S);
ElemType e;//创建栈int len;printf("Please enter the length of data you want to insert!(Length < %d)\n", MaxSize);scanf("%d",&len);printf("Please enter %d elements one by one in order!\n", len);while(len--){scanf("%d",&e);Push(S, e);}PrintStack(S);//入栈printf("please input the element you want to input to the stack\n");scanf("%d",&e);Push(S,e);printf("You have done it!\n");PrintStack(S);//出栈printf("please input the element you want to out \n");Pop(S, e);printf("the %d have be POPPED!\n",e);PrintStack(S);//获取栈顶元素printf("the top element is %d",GetTop(S));return0;}