#include<stdio.h> #include<stdlib.h> #define initsize 100 #define ok 1 #define error 0 typedef int Status; typedef char ElemType; typedef struct{ ElemType *base; ElemType *top; int stacksize; }SqStack; static SqStack *S; Status InitStack(SqStack *S){ S->base=(ElemType *)malloc(initsize*sizeof(ElemType)); if(!S->base){ printf("分配内存失败!"); exit(error); } S=->top=S->base; S->stacksize=initsize; return ok; } Status StackEmpty(SqStack *S){
if(S->base==S->top){
return true;
}else{
return false;
}
}
Status DestroyStack(SqStack *S){ free(S->base);
return 0; } Status ClearStack(SqStack *S); Status StackEmpty(SqStack *S); Status StackLength(SqStack *S); Status GetTop(SqStack *S,ElemType e){ if(S->top!=S->base){ e=*(S->top-1);//非空栈的栈顶指针始终在栈顶元素的下一个位置 } return e; } Status Push(SqStack *S,ElemType e){ if(S->top-S->base>=initsize){ S->base=(ElemType *)realloc(S->base,(initsize+10)*sizeof(ElemType)) if(!S->base){ printf("内存分配失败"); exit(error); } S->stacksize+=10; S->top=S->base+S->stacksize;//此处的initsize为没有重新分派的initsize因为分配了空间不代表着top就要指向最顶 } *S->top++=e; return ok; } Status Pop(SqStack *S,ElemType *e){ if(S->top!=S->base){ S->top--; e=*S->top; return ok; }else{ return error; } } Status StackTraverse(const SqStack *S){ int *p; if(S->base==S->top){ exit(error); }else{ for(p=S->base;p<S->top;p++){ printf("%c \n",*p); } } } void main(){ int m; InitStack(S); printf("请输入一个入栈元素\n",&m); Push(S,m); StackTraverse(S); }