顺序栈
一、相关概念
- 栈和队列是操作受限的线性表,是限定性的数据结构;
- 栈分为顺序栈和链式栈
- 栈只能在一端进行操作(插入、删除)
- 栈是限定仅在表尾进行插入或删除操作的线性表,因此,对栈来说,表尾端具有特殊含义,称为栈顶(top),相应的,表头端称为栈底(bottom)
- 不含元素的空表称为空栈
二、顺序栈的结构
typedef struct Stack
{
int* base; //指向动态内存
int top; //栈顶指针,实际上是下标
int stacksize; //栈的总大小
}Stack, *PStack;
三、顺序栈的实现
#define INIT_SIZE 10
void InitStack(PStack ps)
{
assert(ps != NULL);
ps->base = (int*)malloc(INIT_SIZE * sizeof(int*));
ps->top = 0;
ps->stacksize = INIT_SIZE;
}
static bool IsFull(PStack ps)
{
return ps->top == ps->stack;
}
static void Inc(PStack ps)
{
ps->stacksize *= 2;
ps->base = (int*)realloc(ps->base, ps->stacksize * sizeof(int));
assert(ps->base != NULL);
}
bool Push(PStack ps, int val)
{
assert(ps != NULL);
if(IsFull)
Inc(ps);
ps->base[ps->top++] = val;
return true;
}
bool GetTop(PStack ps, int *rtval)
{
assert(ps != NULL);
if(IsEmpty(ps))
return false;
*rtval = ps->base[ps->top - 1];
return true;
}
bool Pop(PStack ps, int *rtval)
{
assert(ps != NULL);
if(IsEmpty(ps))
return false;
*rtval = ps->base[--ps->top];
return true;
}
bool IsEmpty(PStack ps)
{
return ps->top == 0;
}
int GetLength(PStack ps)
{
assert(ps != NULL);
return ps->top;
}
void Clear(PStack ps)
{
assert(ps != NULL);
ps-> top = 0;
}
void Destroy(PStack ps)
{
assert(ps != NULL);
free(ps->base);
ps->base = NULL;
ps->top = 0;
ps-> =stacksize;
}
四、顺序栈的总结
- 栈的特点:后进后出,后来的反而需要先服务(访问受限的线性表)
- 栈又分为顺序栈和链式栈
- 本篇顺序栈为不定长的顺序栈,能自动扩容
- 栈只能在一端进行插入和删除,插入和删除这一端称之为栈顶,另一端称之为栈底
- 顺序栈的栈顶在尾部,因为入栈和出栈的时间复杂度为O(1)