/*順序表實現棧的一系列操做*/ #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; } }