栈是一种特殊的线性结构,对数据增加及其删除只能在一端进行操作。 进行数据删除及增加的一端为栈顶,另一端为栈底。 增加数据为压栈。删除数据为出栈。
ctypedef int StackTypeDate;
typedef struct stack
{
StackTypeDate* arr;
int top;
int capacity;
}Stack;
cvoid InitStack(Stack* ps)
{
assert(ps);
ps->arr = NULL;
ps->top = ps->capacity = 0;
}
压栈的时候要察看栈是不是满了,以及它为空的情况。
cvoid StackPush(Stack* ps, StackTypeDate x)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
ps->arr = (StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate) * newcapacity);
ps->capacity = newcapacity;
}
ps->arr[ps->top] = x;
ps->top++;
}
cvoid StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
cStackTypeDate StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
//注意这里的减一
return ps->arr[ps->top-1];
}
cint StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
cbool StackEmpty(Stack* ps)
{
assert(ps);
return ps->capacity == 0;
}
cvoid StackDestroy(Stack* ps)
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}