/**************顺序栈的实现,参考了严蔚敏《数据结构》*******************/
//使用前要用typedef把status,SElemType定义为合法数据类型
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
typedef struct {
SElemType *base;
SElemType *top;
int StackSize;
}SqStack;
/************ 初始化一个栈,初始化后栈为空*************/
Status InitStack(SqStack &S){
S.base = (SElemType*) malloc( sizeof(SElemType) * STACK_INIT_SIZE );
if(!S.base)
return ERROR;
S.top = S.base;
S.StackSize = STACK_INIT_SIZE;
return OK;
}
/**************判断栈是否为空*********************/
Status StackEmpty(SqStack S){
if(S.base == S.top)
return OK;
return ERROR;
}
/**************将栈清空*****************/
Status ClearStack(SqStack S){
S.top = S.base;
return OK;
}
/**********销毁一个栈**********/
Status DestroyStack(SqStack &S){
free(S.top);
free(S.base);
return OK;
}
/**************压栈,压入的值为e*******************/
Status Push(SqStack &S, SElemType e){
if(S.top-S.top >= S.StackSize){
S.base = (SElemType *) realloc (S.base,(S.StackSize + STACKINCREMENT) * sizeof (SElemType));
if(!S.base)
return ERROR;
S.top = S.base + S.StackSize;
S.StackSize = S.StackSize + STACKINCREMENT;
}
*S.top = e;
S.top++;
return OK;
}
/**************出栈,将刚在栈顶的值放在e中*******************/
Status Pop(SqStack &S, SElemType &e){
if(S.base == S.top){
prSElemTypef("栈已空,删除错误!");
return ERROR;
}
--S.top;
e = *S.top;
return OK;
}
/**************得到栈顶值,放在e中*******************/
Status GetTop(SqStack S, SElemType &e){
if(S.top = S.base){
prSElemTypef("栈为空");
return ERROR;
}
e = *(S.top - 1);
return OK;
}
/**************得到栈长度******************/
SElemType StackLength(SqStack S){
SElemType length = 0;
if(S.base == S.top)
return 0;
for(SElemType * i = S.base; i != S.top; i++){
++length;
}
return length;
}