共享顺序栈的实现
#include<iostream.h> #include<stdlib.h> //exit的原型定义 #define STACK_INIT_SIZE 8 #define STACKINCREMENT 10 #define OVERFLOW -2 #define OK 1 #define ERROR 0 typedef int Status; typedef char SElemType; typedef struct { SElemType *base; //栈底指针 SElemType *top; //栈顶指针 int stacksize; // 当前已分配的栈空间 }SqStack; void InitStack(SqStack &S) { //构造一个空的顺序栈 S S.base=new SElemType[STACK_INIT_SIZE]; if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=STACK_INIT_SIZE; } Status StackEmpty(SqStack S) { //判栈空 if(S.top==S.base) return OK; //空则返回1 else return ERROR; //不空返回0 } Status StackFull(SqStack S) { //判栈满 if(S.top-S.base>=S.stacksize) return OK; //判栈满,满则返回1 else return ERROR; //否则返回0 } Status push(SqStack &S,SElemType x) { //插入元素x为新的栈顶元素 if(StackFull(S)) return ERROR; *S.top++=x; return OK; } Status pop(SqStack &S,SElemType &e) { //若栈空返回0,否则栈顶元素退出到e并返回1 if(StackEmpty(S)) return ERROR; --(S.top); e=*(S.top); return OK; } void StackTravers(SqStack S) { SqStack p=S; while(p.top>S.base) cout<<*--p.top<<" "; cout<<endl; } void GetTop(SqStack S,SElemType &e) { if(StackEmpty(S)) cout<<"stack is empty!\n"; e=*(S.top-1); } void main() { SqStack S; SElemType e; InitStack(S); for(char ch='a';ch<='g';ch++) push(S,ch); StackTravers(S); cout<<"input Element e="; cin>>e; if(!push(S,e)) cout<<"Stack Full!\n"; StackTravers(S); GetTop(S,e); cout<<e<<endl; StackTravers(S); }