1,定义结构体元素:
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define TRUE 1
#define FALSE 0
typedef struct {
SElemType * base; //栈顶指针
SElemType *top; //栈底指针
int stacksize; //栈可使用的最大容量
} SqStack;
按初始分配量进行第一次存储分配,base为栈底指针,始终指向栈底。top为栈顶指针,初值指向栈底,每插入一个元素,top增1;每删除一个元素,top减1,top始终在栈顶元素的下一个位置上。
2,栈的初始化:
//初始化
Status InitStack (SqStack &S){
S.base=(SElemType *)malloc (STACK_INIT_SIZE *sizeof(SElemType)); //申请分配内存
if (! S.base) exit (OVERFLOW); //S.base 为NULL 输出OVERFLOW
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
3,取栈顶元素:
//取栈顶元素
//取出并不删除
Status GetTop(SqStack S, SElemType &e){
if (S.top = = S.base) return ERROR;
e= * (S.top-1);
return OK;
}
4,入栈:
//入栈
Status Push(SqStack &S, SElemType e){
if (S.top - S.base>= S.stacksize){
S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType))
//扩大一块内存
if(!S.base) exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;//top指针指向栈顶元素上方
return OK;
}
5,出栈:
//出栈
Status Pop(SqStack &S, SelemType &e){
if( S.top= =S.base) return ERROR;
e=*--S.top; //出栈,栈顶元素移除,栈顶指针本身向下移动
return OK;
}
6,销毁栈:
Status DestroyStack(SqStack &S)
{
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
return OK;
}
7,清空栈:
Status ClearStack(SqStack &S)
{
S.top = S.base;
return OK;
}
8,计算栈的长度:
Status StackLength(SqStack S)
{
return S.top - S.base;
}
栈的长度,栈顶指针减去栈底指针
9,判断是否为空栈:
Status StackEmpty(SqStack S)
{
if(S.top != S.base)
return FALSE;
else
return TRUE;
}
Status StackEmpty(SqStack S)
{
if(S.top == -1)
return TRUE;
else{
return FLASE;
}
}