//栈
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;//数据量
int capacity;//容量
}ST;
bool STEmpty(ST* pst)
{
assert(pst);
/*if (pst->top == 0)
{ return true; }
else
{ return false; }*/
return pst->top == 0;
}
// 初始化栈
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
//pst->top = -1; // top 指向栈顶数据
pst->top = 0; // top 指向栈顶数据的下一个位置
pst->capacity = 0;
}
// 销毁栈
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capacity = 0;
}
//入栈
void STPush(ST* pst, STDataType x)
{
if (pst->top == pst->capacity)
{
int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
pst->a = tmp;
pst->capacity = newCapacity;
}
pst->a[pst->top] = x;
pst->top++;
}
//出栈
void STPop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
pst->top--;
}
//获取栈顶元素
STDataType STTop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
return pst->a[pst->top - 1];
}
//获取栈内元素个数
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
栈(c语言)
最新推荐文章于 2024-10-15 22:45:07 发布