顺序栈
栈是受限的线性表,逻辑结构仍然是一对一的关系。仅在表尾进行插入、删除操作。即先进后出、后进先出。
顺序栈:顺序开辟一块空间存储栈中的每个元素。
初始化
#define STACKSIZE 10
typedef struct SqStack{
ElemType *base,*top;
int stacksize;
}SqStack;
int InitStack(SqStack &S){
S.base=(ElemType *)malloc(sizeof(ElemType)*STACKSIZE);
if(!S.base)exit(-2);
S.top=S.base;
S.stacksize=STACKSIZE;
return OK;
}
判断是否为空栈
int IsEmpty(SqStack &S){
if(S.top==S.base)return 1;
else return 0;
}
入栈
1、判断栈是否为空,栈满开辟更大的空间;
2、将值存入栈顶所指空间;
3、栈顶指针上移。
int Push(SqStack &S,Elemtype e){
if(S.top-S.base>=S.stacksize){
S.base=(ElemType )realloc(S.base,sizeof(ElemType)(S.stacksize+STACKINCREMENT));
if(!S.base)exit(0);
S.top=S.base+S.stacksize;
S.stacksize+=STACKSIZEMEXT;}
*S.top=e;
S.top++;
return OK;
}
出栈
1、判断栈是否为空,若空则出错;
2、栈顶指针下移;
3、取栈顶元素。
int Pop(SqStacksize &S,Elemtype &e){
if(S.top==S.base)return ERROR;
S.top–;
e=*S.top-1;
return OK;
}
取栈顶元素
int GetStack(SqStack S,ElemType &e){
if(S.top==S.base)return ERROR;
e=*(S.top-1);
return OK;
}
栈的长度
int StackLength(SqStack S){
return S.top-S.base;
}
清空顺序栈
int ClearStack(SqStack&S){
if(S.base)S.top=S.base;
return OK;
}
销毁顺序栈
int DestroyStack(SqStack &S){
if(S.base){
free(S.base);
S.stacksize=0;
S.base=S.top=NULL;}
return OK;
}