代码:
//用顺序存储结构实现的顺序栈
#include<stdio.h>
#define MAXSIZE 10
typedef int bool;
#define true 1
#define false 0
typedef struct{
int data[MAXSIZE]; //静态数组存放栈中元素
int top; //当前栈顶元素
}SqStack;
void initStack(SqStack *S){
S->top=-1;
}
bool push(SqStack *S,int e){
if(S->top==MAXSIZE-1){
return false;
}
S->top=S->top+1;
S->data[S->top]=e;
return true;
}
bool pop(SqStack *S,int *e){
if(S->top==-1){
return false;
}
*e=S->data[S->top];
S->top=S->top-1;
return true;
}
bool getTop(SqStack S,int *e){
if(S.top==-1){
return false;
}
*e=S.data[S.top];
return true;
}
void printStack(SqStack S){
for(int i=S.top;i>=0;i--){
printf("%d ",S.data[i]);
}
printf("\n");
}
int main(){
SqStack S;
int e;
initStack(&S);
for(int i=1;i<=5;i++){
push(&S,i);
}
printStack(S);
pop(&S,&e);
printStack(S);
getTop(S,&e);
printf("此时栈顶元素为%d\n",e);
return 0;
}
运行结果: