目录
一、栈
1.1 栈的定义和结构
栈:一种特殊的线性表。栈中的数据元素遵守先进后出的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
1.2 栈的函数实现
1.2.1 初始化
void StackInit(ST* st)
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void StackInit(ST* st)
{
assert(st);
st->a = NULL;
st->top = st->capacity = 0;
}
1.2.2 入栈
void StackPush(ST* st, STDataType x)
void StackPush(ST* st, STDataType x)
{
assert(st);
if (st->top == st->capacity)
{
int newcapacity = st->capacity == 0 ? 4 : st->capacity * 2;
STDataType* tmp = (STDataType)realloc(st->a,newcapacity*sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
st->a = tmp;
st->capacity = newcapacity;
}
st->a[st->top] = x;
st->top++;
}
1.2.3 出栈
void StackPop(ST* st)
bool StackEmpty(ST* st)//判断栈是否为空
{
assert(st);
return st->top == 0;
}
void StackPop(ST* st)
{
assert(st);
assert(!StackEmpty(st));
st->top--;
}
1.2.4 获取栈顶元素
STDataType StackTop(ST* st)
STDataType StackTop(ST* st)
{
assert(st);
assert(!StackEmpty(st));
return st->a[st->top - 1];
}
1.2.5 栈的长度
int StackSize(ST* st)
int StackSize(ST* st)
{
assert(st);
return st->top;
}