#include
#include
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//定义函数返回的类型
typedef int Status;
#define STACK_INIT_SIZE 100 //顺序栈存储空间的初始分配量
#define STACKINCREMRNT 10 //顺序栈存储空间的分配增量
typedef char SElemType;
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
//初始化栈
Status InitStack(SqStack &S) {
S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (S.base == NULL) {
exit(OVERFLOW);
}
S.top = S.base; //没有元素时,base和top指向同一个区域
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status StackEmpty(SqStack S) {//不需要改变栈的元素,不需要按引用传递
if (S.base == S.top) {//top和base相同时,说明没有元素,返回true
return TRUE;
} else {
return FALSE;
}
}
Status Push(SqStack &S, SElemType e) {
if(S.top - S.base >= S.stacksize) {//top指针总是指向顶元素的下一个位置,top-base等于栈包含的元素个数
S.base = (SElemType*)realloc(S.base, (S.stacksize + STACKINCREMRNT)*sizeof(SElemType));//超过初始分配空间,则使用realloc函数重新分配空间
if(S.base == NULL) {
exit(OVERFLOW);
}
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMRNT;
}
*S.top++ = e;//++后置,先把e的值赋给top所指位置,然后top加一
return OK;
}
int StackLength(SqStack S) {
return S.top - S.base;
}
Status Pop(SqStack &S, SElemType &e) {
if (S.top == S.base) {//相等时,栈为空
return ERROR;
}
e = * --S.top;
return OK;
}
Status DestoryStack(SqStack &S) {
free(S.base);//释放base,注意base和top指向同一位置,不可重复释放
// free(S.top);
return OK;
}
#include "SqStack.h"
int main () {
SqStack S;
printf("%sn", "初始化栈");
InitStack(S);
printf("栈为%sn", (StackEmpty(S)?"空":"非空"));
printf("%sn", "依次进栈元素a,b,c,d,e");
Push(S, 'a');
Push(S, 'b');
Push(S, 'c');
Push(S, 'd');
Push(S, 'e');
printf("栈为%sn", (StackEmpty(S)?"空":"非空"));
printf("栈的长度为%dn", StackLength(S));
SElemType e;
while(Pop(S,e) != ERROR) {
printf("输出栈顶元素%cn", e);
}
printf("出栈序列%sn", "e,d,c,b,a");
printf("栈为%sn", (StackEmpty(S)?"空":"非空"));
printf("%sn", "释放栈");
DestoryStack(S);
}