#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *top;//栈顶
SElemType *base;//栈底
int stacksize;
}SqStack;
//顺序栈的初始化
Status InitStack(SqStack *S) {
S->base=(SElemType*)malloc(sizeof(SElemType)*MAXSIZE);
if(S->base==NULL){
return ERROR;
}
S->top=S->base;
S->stacksize=MAXSIZE;
return OK;
}
//入栈
Status Push(SqStack *S,int e){
if(S->top-S->base==S->stacksize)
return ERROR;
*(S->top)=e;
(S->top)++;
return OK;
}
//出栈
Status Pop(SqStack *S,SElemType *e){
if(S->top-S->base==S->stacksize)
return ERROR;
--(S->top);
*e=*(S->top);
return OK;
}
//栈顶元素
Status GetTop(SqStack S){
if(S.top!=S.base)
return *(S.top-1);
}
//遍历
void TravelList(SqStack S){
int *p;
p=S.base;
while(p!=S.top){
printf("%d ",(*p));
++p;
}
}
int main() {
int n,e,i;
SqStack S;
//初始化
if(InitStack(&S)){
printf("初始化完成\n");
}
//入栈
printf("输入n个元素。请输入n值:");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&e);
Push(&S,e);
}
//出栈
TravelList(S);
printf("\n");
Pop(&S,&e);
printf("出栈的元素为:%d\n",e);
//栈顶元素
TravelList(S);
printf("\n");
GetTop(S);
printf("栈顶元素为:%d",e);
return 0;
}