1.结构
typedef int STDatatype;
typedef struct Stack
{
STDatatype* a;
int capacity;
int top; // 初始为0,表示栈顶位置下一个位置下标
}ST;
这里的top初始为0,表示栈顶下一个位置;
2.初始化
void StackInit(ST* ps)
{
assert(ps);
//ps->a = NULL;
//ps->top = 0;
//ps->capacity = 0;
ps->a = (STDatatype*)malloc(sizeof(STDatatype)*4);
if (ps->a == NULL)
{
perror("malloc fail");
exit(-1);
}
ps->top = 0;
ps->capacity = 4;
}
3.销毁
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
4.栈顶插入一个元素(压栈)
void StackPush(ST* ps, STDatatype x)
{
assert(ps);
//
if (ps->top == ps->capacity)
{
STDatatype* tmp = (STDatatype*)realloc(ps->a, ps->capacity * 2 * sizeof(STDatatype));
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity *= 2;
}
ps->a[ps->top] = x;
ps->top++;
}
插入元素时如果栈满了要用relloc扩容,因为top是从0开始的,表示栈顶的下一个位置,所以把元素先存在top下标,再对top++;
5.出栈
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
出栈只需要用top限制,不需要删除元素;
6.大小
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
很简单,无需多言;
7. 找到栈顶元素并返回;
STDatatype StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
8.判断栈是否为空
bool StackEmpty(ST* ps)
{
assert(ps);
/*if (ps->top == 0)
{
return true;
}
else
{
return false;
}*/
return ps->top == 0;//逻辑运算
}