我们都知道,栈是一种线性的数据结构。那么用顺序存储的栈,则称为顺序栈
首先,我们来看一下顺序栈的抽象数据类型
首先,*elem是作为存储空间的基址,到时候将会使用malloc开辟的一段连续存储空间作为栈的操作空间
typedef int ElemType;
typedef struct {
ElemType* elem; // 存储空间的基址
int top; // 栈顶元素的下一个位置,简称栈顶位标
int size; // 当前分配的存储容量
int increment; // 扩容时,增加的存储容量
} SqStack; // 顺序栈
#define OVERFLOW -1
#define OK 1
#define ERROR 0
#define TRUE 2
#define FALSE -2
#define INITSIZE 5 //栈的初始容量
#define INCREMENT 2 //栈扩容时的增量
typedef int Status;
Status InitStack_Sq(SqStack& S, int size, int inc);
Status StackEmpty_Sq(SqStack S);
Status Push_Sq(SqStack& S, ElemType e);
Status Pop_Sq(SqStack& S, ElemType& e);
下面来看看我们定义的初始化,判空,入栈出栈操作
Status InitStack_Sq(SqStack& S, int size, int inc) { // 初始化空顺序栈S
S.elem = (ElemType*)malloc(size * sizeof(ElemType)); // 分配存储空间
if (NULL == S.elem) return OVERFLOW;
S.top = 0; // 置S为空栈
S.size = size; // 初始容量值
S.increment = inc; // 初始增量值
return OK;
}
//进栈
Status Push_Sq(SqStack& S, ElemType e) { // 元素e压入栈S
ElemType* newbase;
if (S.top >= S.size) { // 若栈顶位标已到达所分配的容量,则栈满,扩容
newbase = (ElemType*)realloc(S.elem, (S.size + S.increment) * sizeof(ElemType));
if (NULL == newbase) return OVERFLOW;
//Add your code here: 调整S.elem和S.size
S.elem = newbase;
S.elem[S.top++] = e;
S.size += S.increment;
return OK;
}
//Add your code here: e入栈,并将S.top加1
S.elem[S.top++] = e;
return OK;
}
//出栈
Status Pop_Sq(SqStack& S, ElemType& e) { // 栈顶元素出栈,赋给元素e
//add your code here
if (0 == S.top)
return ERROR;
//Add your code here: e出栈,并将S.top减1
e = S.elem[--S.top];
return OK;
}
//判空操作
Status StackEmpty_Sq(SqStack S) { // 判断栈S是否空,若空则返回TRUE,否则FALSE
if (0 == S.top)
return TRUE;
else
return FALSE;
}
在入栈操作中要管理好top栈顶位标的位置,使top始终指向栈顶的下一个位置。