1.栈的基本结构
栈的特点是先进后出,是一种线性结构。我们有两种选择,一、链表,二、数组。要实现先进后出,使用链表后出的代价太大,数组是较优的选择。
栈
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capicity;
}ST;
2.栈的接口函数
初始化
void StackInit(ST* ps);
void StackInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a == NULL)
{
printf("malloc fail!");
exit(-1);
}
ps->top = 0, ps->capicity = 4;
}
销毁
void StackDestory(ST* ps);
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capicity = 0;
}
入栈
void StackPush(ST* ps, STDataType x);
void StackPush(ST* ps, STDataType x)
{
assert(ps);
CheckStack(ps);
ps->a[ps->top++] = x;
}
出栈
void StackPop(ST* ps);
void StackPop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
printf("%d ",StackTop(ps));
ps->top--;
}
栈顶
STDataType StackTop(ST* ps);
STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
栈数据长度
int StackSize(ST* ps);
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
栈是否为空
bool StackEmpty(ST* ps);
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top==0;
}
检查空间,如果满了,进行增容
void CheckStack(ST* ps);
void CheckStack(ST* ps)
{
if (ps->top == ps->capicity)
{
ST* tmp = realloc(ps->a, sizeof(STDataType) * 2 * ps->capicity);
if(tmp==NULL)
{
printf("realloc fail");
exit(-1);
}
else
{
ps->a = tmp;
ps->capicity *= 2;
}
}
}
3.栈的使用
int main()
{
ST st;
StackInit(&st);
StackPush(&st, 1);
StackPush(&st, 2);
StackPush(&st, 3);
StackPush(&st, 4);
StackPush(&st, 5);
StackPop(&st);
StackPop(&st);
StackPop(&st);
StackPop(&st);
StackDestory(&st);
return 0;
}