#include<stdio.h>#include<stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define SELemTYpe int#define Status int#define OK 1#define ERROR 0typedefstruct{
SELemTYpe * base;//the base of the stack
SELemTYpe *top;//the head of the stackint 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;//initilize the stack}
得到栈的栈顶元素
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){// in the situation that the nternal storage is not enoughif(S.top-S.base>=S.stacksize){
S.base =(SELemTYpe*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SELemTYpe));// realloc the spaceif(!S.base)exit(OVERFLOW);
S.top = S.base + S.stacksize;// redefine the top
S.stacksize += STACKINCREMENT;}*S.top++= e;//assign the S.top first and then add the S.topreturn OK;}
判断栈是否为空
Status StackEmpty(SqStack S){if(S.base == S.top)return OK;return ERROR;}
弹出栈顶的元素
Status pop(SqStack &S,SELemTYpe &e){if(S.base == S.top)return ERROR;
e =*--S.top;return OK;}
遍历栈中的元素
Status StackTraverse(SqStack S){
SELemTYpe *p;
p = S.base;for(; p<S.top; p++){printf("%d ",*p);}return OK;}