栈是一个特殊的线性表,它只能从一端插入和同一端删除。
栈的插入操作一般叫做入栈和进栈,栈的删除操作一般叫做出栈。
1. 栈的初始化
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
//top指向栈顶元素的下一个位置
pst->top = 0;
//top指向栈顶元素
// pst->top=-1;
pst->capacity = 0;
}
a表示栈顶元素的地址
top根据赋值不同有不同的意思,top=0时,top指向栈顶元素的下一个位置;top=-1时,top指向栈顶元素;
capacity表示栈里元素个数
栈的初始化不与顺序表和链表一样简单,不同的初始化代表着不同的意思,
为什么top的值不同,表达的意思不同呢?
这是因为我们创立的栈是模仿顺序表的,因此我们想要top来表示下标的变换情况,当栈里没有元素的时候,top=0却已经存在,因此这互相矛盾了,因此top=0时表示栈的下一个元素;当top=-1时,因为没有下标为-1的,此时栈里也没有元素,所以此时top表示栈顶元素的位置;
下述都以top=0;
2. 栈的销毁
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
判空很重要
3 入栈
void STPush(ST* pst, STDataType x)
{
assert(pst);
//扩容
if (pst->top==pst->capacity)
{
int newcapasity = pst->capacity == 0 ? 4 : pst->capacity * 2;
STDataType* tmp = (STDataType*)realloc(pst->a, newcapasity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail!");
return;
}
pst->a = tmp;
pst->capacity = newcapasity;
free(tmp);
tmp = NULL;
}
pst->a[pst->top++]=x;
}
如果栈里还有空间就直接插入,没有空间就扩容
此时我的代码选择的是top=0的情况,因此当top=capacity时,空间已满或者空间等于0,
因此如果空间已满,就扩大两倍,如果空间为0,就开辟4个空间,
不能原地扩容,因为可能扩容失败导致原来的数据丢失,先将扩容的空间用tmp存储,扩容失败直接返回,成功再重新赋值;
4. 出栈
//出栈
void STPop(ST* pst)
{
assert(pst);
assert(pst->top>0);
pst->top--;
}
不能传递空指针且栈不能为空;
5. 获取栈顶数据
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst->top);
return pst->a[pst->top-1];
}
跟上述一致,直接返回栈顶元素
6.判断栈是否为空
bool STEmpty(ST* pst)
{
assert(pst);
assert(pst->top);
return pst->top == NULL;
}
如果 top等于空,则等式成立返回true,不等于空则等式不成立,返回false;
7 获取栈的元素个数
int STSize(ST* pst)
{
assert(pst);
assert(pst->top);
return pst->top;
}
top和capacity都能表示元素个数
10万+

被折叠的 条评论
为什么被折叠?



