数据结构------栈的讲解(超详细)-腾讯云开发者社区-腾讯云
#include"Stack.h"
void STInit(ST* ps)
{
ps->arr = NULL;
ps->capacity = ps->top = 0; //总空间个数和有用空间个数都初始化为0
}
void STDestroy(ST* ps)
{
if (ps -> arr) //先判断是否进行动态内存开辟了
{
free(ps -> arr);
}
ps->capacity = ps->top = 0;
}
void STPush(ST* ps, STDataType x) //类似顺序表的尾插
{
if (ps->capacity == ps->top)
{
int newcaopacity = ps->capacity == 0 ? 4 : 2 * ps -> capacity;
STDataType* arr1 = (STDataType*)realloc(ps->arr, newcaopacity * sizeof(STDataType));
assert(arr1);
ps->arr = arr1;
ps->capacity = newcaopacity;
} //扩容完成
ps->arr[ps->top++] = x;
}
bool panduan(ST * ps)
{
assert(ps);
return ps -> top == 0; //这个是来判断栈是不是空了
}
void STPop(ST* ps)
{
assert(ps);
assert(!panduan(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
return ps->arr[ps->top - 1];
}
int STSize(ST* ps)
{
return ps->top;
}