1.结构体的组成
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
a:记录数组地址
top:记录栈顶位置
capacity:数组的容量
2.函数的实现
1.结构体初始化
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = 0;
// 表示top指向栈顶元素的下一个位置
pst->top = 0;
// 表示top指向栈顶元素
//pst->top = -1;
}
因为 top相当于数组的下标
2.整个栈的销毁
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capacity = 0;
}
3.入栈,栈的扩容
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
int newcapacity = pst->capacity == 0 ? 4 : pst->capacity +2;
STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType) * newcapacity);
if (tmp == NULL)
{
perror("realloc");
return;
}
pst->a = tmp;
pst->capacity = newcapacity;
}
pst->a[pst->top] = x;
pst->top++;
}
1.当top=capacity
realloc分配的空间是连续的,所以可以把它当数组用。把分配的内存地址赋值给a,然后扩容。
2.top<capacity
a存的是内存的地址,所以把x赋值a内地址的内存中,然后top增加
4.出栈
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
只需要把top的值减一,之后在入栈时,直接x覆盖掉之前的值
5.获取栈顶元素
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[pst->top - 1];
}
因为top初始值为0,所以这里减一访问,[ ]解引用符号。
6.判断栈是否为空
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == 0;
}
C语言没有bool类型,要引用头文件#include<stdbool.h>
7.获取栈所含元素个数
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
恭喜你学完啦,快去奖励自己一下吧!