栈结构
typedef struct Stack
{
int* a;
int top;
int capacity;
}S;
capacity是容量
top栈顶的位置
初始化
void Init(S* ps)//初始化可以给空,也可以给值
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;//top初始化成0和-1的意义不同
//初始化成0表示top标记栈顶元素的后一个位置
}
入栈
void Push(S* ps, int x)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
ps->a = (int*)realloc(ps->a, newcapacity * sizeof(int));
if (ps->a == NULL)
exit(-1);
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
出栈
void Pop(S* ps)
{
//assert(ps);
//if (!Empty(ps))
//{
// --ps->top;
//}
assert(ps);
assert(ps->top > 0);
--ps->top;
}
获取栈顶元素
int Top(S* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
栈空判断
bool Empty(S* ps)
{
assert(ps);
return ps->top == 0;
}