栈(数组模拟)
结构体定义
cpp
复制代码
typedef int StackData;
typedef struct StackNode
{
StackData* a;
int top;
int capacity;
}Stack;
初始化
cpp
复制代码
void StackInit(Stack* st)
{
assert(st);
StackData* tmp = (StackData*)malloc(sizeof(StackData) * 4);
if (tmp == NULL)
{
perror("malloc fail");
return;
}
st->a = tmp;
st->capacity = 4;
st->top = -1;
}
销毁和判空
cpp
复制代码
void StackDestory(Stack* st)
{
assert(st);
st->a = NULL;
st->top = st->capacity = 0;
}
bool Stack_Empty(Stack* st)
{
return st->top == -1;
}
入栈和出栈
cpp
复制代码
void StackPush(Stack* st, StackData x)
{
assert(st);
if (st->top + 1 == st->capacity)
{
StackData* tmp = (StackData*)realloc(st->a, sizeof(StackData) * st->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
st->a = tmp;
st->capacity *= 2;
}
st->a[++st->top] = x;
}
void StackPop(Stack* st)
{
assert(st);
assert(!Stack_Empty(st));
st->top--;
读取个数和取顶部数据
cpp
复制代码
int StackSize(Stack* st)
{
assert(st);
return st->top + 1;
}
int StackTop(Stack* st)
{
assert(st);
assert(!Stack_Empty(st));
return st->a[st->top];
}
括号匹配