顺序栈
采用顺序结构的栈称为顺序栈,即需要用一片地址连续的空间来存储栈的元素。=>可用一个数组来实现,并指定栈顶元素位于序列末端,每当新元素入栈或出栈时,数组中其他元素可不改变位置,只需改变栈顶位置即可。=>由于c语言数组的大小是预先固定的,空间存满后,则不能继续插入新元素;因此,可以采用动态分配的一段连续的存储空间来储存栈的元素。
顺序栈的类型定义
typedef struct{
ElemType * elem; //存储空间的基址
int top; //栈顶元素的下一个位置,简称栈顶位标
int size; //当前分配的存储空间
int increment; //扩容时,增加的存储容量
}SqStack; //顺序栈
- 初始化顺序栈
将顺序栈S置为初始容量为size的空栈。算法复杂度O(1).
Status InitStack_Sq( SqStack &S, int size, int inc){
//分配存储空间
S.elem = (ElemType * )malloc(size * sizeof(ElemType));
if(NULL == S.elem)return OVERFLOW; //空间分配失败
S.top = 0; //置S为空栈
S.size = size; //初始容量值
S.increment = inc; //初始增量值
}
- 销毁顺序栈
Status DestoryStack_Sq(SqStack &S)
{
S.size = 0;
S.increment = 0;
free(S->elem); //释放顺序栈分配的空间
}
- 判断顺序栈是否为空
Status StackEmpty_Sq(SqStack &S){
if(S.top == 0)return TRUE; //若栈顶位标为0,说明此时栈为空
else return FALSE;
}
- 清空栈S
Status ClearStack_Sq(SqStack &S){
if(S == NULL){
printf("顺序栈不存在!\n");
return;
}
S.top = 0; //将栈顶位标置为栈底,此时将栈为空栈
printf("顺序栈清空成功!\n");
}
- 元素压栈
Status Push_Sq(SqStack &S, ElemType e){
ElemType * newbase;
if(S.top >= S.size){//若栈顶位标达到所分配容量,则栈满,扩容
newbase = (ElemType * )realloc(S.elem,
(S.size + S.increment) * sizeof(ElemType));
if(NULL == newbase)return OVERFLOW;
S.elem = newbase;
S.size += S.increment;
}
S.elem[S.top++] = e;
return OK;
}
- 栈顶元素出栈
Status Pop_Sq(SqStack &S, ElemType &e)
{
if(NULL == S){
printf("此栈不存在!\n");
exit(-1);
};
if (pS->top <= 0)
{
printf("栈为空!\n");
exit(-1);
}
else
{
e = S.elem[S.top];
S.top--;
return e;
}
}
- 取栈顶元素
Status GetTop_Sq(SqStack &S, ElemType &e)
{
if(NULL == S){
printf("此栈不存在!\n");
exit(-1);
};
if (pS->top <= 0)
{
printf("栈为空!\n");
exit(-1);
}
else
{
e = S.elem[S.top];
return e;
}
}
- 如有错误,欢迎指正。