数据结构之栈和队列
栈是一种特殊的线性结构,拥
有先进后出的特点。
栈一种特殊的线性结构,用顺序表实现更为简单。
栈的结构
由于栈是尾插和尾删,,因此使用顺序表的结构相对简单。
栈的实现
初始化代码:
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = -1;
}//起初top是指向-1,元素的统计更加方便,先top++再插入。
//如果指向0,那就先插入在加加。
每插入一个元素top就加1,size加加,当top与capacity相等便会进行扩容
插入元素代码:
void STDpush(ST* ps, STDataType x)
{
assert(ps);//直接扩容,将realloc当作malloc,使用
ps->top++;//提前自增
if (ps->capacity == ps->top)
{
int newacapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* temp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newacapacity);
if (temp)
{
ps->a = temp;
ps->capacity = newacapacity;
}
else {
perror("realloc");
}
}
ps->a[ps->top] = x;
}
栈元素的弹出
栈元素的弹出很简单,只需要将top-1,不过在减去1之前需要对栈检查是否为空
void STPop(ST* ps)
{
assert(ps);
assert(ps->top != -1);//检查是否为空
ps->top--;
}
栈的实际长度
栈的实际长度看top,不过top要自增一下
int STSize(ST* ps)
{
assert(ps);
return ps->top++;
}
栈顶元素
STDataType STTop(ST* ps)
{
return ps->a[ps->top];
}
判断是否为空
bool STEmpty(ST* ps)
{
bool a = ps->top == -1 ? true : false;
return a;
}
栈的销毁
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a); ps->a = NULL;
ps->capacity = 0;
ps->top = -1;
}