#include<stdio.h> #include<stdlib.h> #define ERROR 0 #define OVERFLOW -2 #define OK 1 #define STACK_INIT_SIZE 5 #define STACKINCREMENT 2 typedef int SElemType; typedef int Status; typedef struct { SElemType *base; SElemType *top; int stacksize; } SqStack; Status InitStack(SqStack &S) { S.base=(SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType)); if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=STACK_INIT_SIZE; return OK; } Status GetTop(SqStack S,SElemType &e) { if(S.top==S.base) return ERROR; e=*(S.top-1); return OK; } Status Push(SqStack &S,SElemType e) { if(S.top-S.base>=S.stacksize) { S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); S.top=S.base+S.stacksize; S.stacksize+=STACKINCREMENT; } *S.top++=e; return OK; } Status Pop(SqStack &S,SElemType &e) { if(S.top==S.base) return ERROR; e=*--S.top; return OK; } int main() { SqStack S; int i; scanf("%d",&S.stacksize); InitStack(S); for(i=0; i<S.stacksize; i++) { scanf("%d",S.top); S.top++; } SElemType *q; q=S.base; while(S.top>q) printf("%d ",*(q++)); printf("\n"); /* 栈中元素的输出的第二种表示方法: for(i=0; i<S.top-S.base; i++) printf("%d ",*(q+i)); printf("\n"); */ int e; GetTop(S,e); q=S.base; printf("e=%d\n",e); scanf("%d",&e); Push(S,e); q=S.base; while(S.top>q) printf("%d ",*(q++)); printf("\n"); printf("e=%d\n",e); Pop(S,e); q=S.base; while(S.top>q) printf("%d ",*(q++)); printf("\n"); printf("e=%d\n",e); return 0; }