栈是一种线性数据结构,它按照 “先进后出”(First In Last Out,FILO)的原则存储和操作数据。这意味着最后插入栈中的元素会最先被取出,就像一摞盘子,最后放上去的盘子会最先被拿走。
栈结构定义: ◦ 使用动态数组存储栈的数据。 ◦ 包含三个主要属性: a:动态分配的数组,用于存储栈中的数据。 capacity:栈的当前容量(即分配的内存大小)。 top:栈顶指针,指向下一个可以插入的位置(同时也是栈中元素的数量)。 2. 初始化操作(StackInit): ◦ 动态分配初始内存空间(大小为4个数据类型单位)。 ◦ 设置栈的初始容量为4。 ◦ 将栈顶指针初始化为0,表示栈为空。 ◦ 如果内存分配失败,打印错误信息并退出程序。 3. 核心逻辑: ◦ 使用 malloc 动态分配内存,确保栈的大小可以根据需要扩展。 ◦ 使用 assert 确保传入的栈指针有效,避免对空指针操作。 ◦ 提供了栈的基本操作框架,为后续实现(如入栈、出栈)奠定了基础。
void StackInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a == NULL)
{
printf("malloc fail\n");
exit(-1);
}
ps->capacity = 4;
ps->top = 0;
}void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}// 入栈
void StackPush(ST* ps, STDataType x)
{
assert(ps);
// 满了-》增容
if (ps->top == ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(STDataType));
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
else
{
ps->a = tmp;
ps->capacity *= 2;
}
}
ps->a[ps->top] = x;
ps->top++;
}void StackPop(ST* ps)
{
assert(ps);
//考虑栈为空的情况;
assert(ps->top > 0);
ps->top--;
}STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}