文章目录
前言
一、什么是栈?
二、栈的实现
1.栈的结构
//栈--用数组实现,后进先出
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;//栈元素的下标
int capacity;//栈元素的个数
}ST;
2.栈的接口
1.初始化
//初始化
void STInit(ST* pst)
{
assert(pst);
pst->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (pst->a == NULL)
{
perror("malloc fail");
return;
}
pst->capacity = 4;
//top不同的初始化方式导致了不同的栈顶元素下标的表示
//1.top初始化为0,则最终top代表栈顶元素的下一个位置的下标
//2.top初始化为-1,则最终top代表栈顶元素的下标
pst->top = 0;
}
2. 销毁
//销毁
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capacity = 0;
}
3. 插入--入栈
//扩容
void CheckCapacity(ST* pst)
{
assert(pst);
if (pst->top == pst->capacity)
{
STDataType* tmp = (STDataType*)realloc
(pst->a, sizeof(STDataType) * pst->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
pst->a = tmp;
pst->capacity *= 2;
}
}
//插入数据
void STPush(ST* pst, STDataType x)
{
assert(pst);
CheckCapacity(pst);
pst->a[pst->top] = x;
pst->top++;
}
4. 删除--出栈
//判空
bool STEmpty(ST* pst)
{
//空的话,返回true
assert(pst);
return pst->top == 0;
}
//删除
void STPop(ST* pst)
{
assert(pst);
//空的栈,不能删除
assert(STEmpty(pst) != true);
pst->top--;
}
5. 返回栈顶元素
//返回栈顶元素
STDataType STTop(ST* pst)
{
assert(pst);
//空的栈不能返回
assert(STEmpty(pst) != true);
STDataType ret = pst->a[pst->top - 1];
return ret;
}
6.返回元素个数及打印
//返回元素个数
int STSize(ST* pst)
{
assert(pst);
//top初始化为0,则最终top代表栈顶元素的下一个位置的下标
//同时,也代表前面的元素的个数
return pst->top;
}
//打印
void Print(ST* pst)
{
while (!STEmpty(pst))
{
printf("%d ", STTop(pst));
STPop(pst);
}
printf("\n");
}