// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
1、判空
#include "stack.h"
#define DEFSTACKSIZE 100
void CheckCapacity(Stack* ps) {
if (ps->size >= ps->capacity)
{
ps->capacity *= 2;
ps->array = (STDataType *)realloc(ps->array, ps->capacity * sizeof(STDataType));
}
}
2、初始化栈
void StackInit(Stack* ps) {
ps->array = (STDataType *)calloc(DEFSTACKSIZE, sizeof(STDataType));
ps->capacity = DEFSTACKSIZE;
ps->size = 0;
}
3、入栈
void StackPush(Stack* ps, STDataType x) {
CheckCapacity(ps);
ps->array[ps->size] = x;
ps->size++;
}
4、出栈
void StackPop(Stack* ps) {
if (ps->size == 0)
{
return;
}
ps->size--;
}
5、获取栈顶元素
STDataType StackTop(Stack* ps) {
if (ps->size == 0)
{
return (STDataType)0;
}
return ps->array[ps->size - 1];
}
6、获取栈中有效元素个数
int StackSize(Stack* ps) {
return ps->size;
}
7、检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps) {
return ps->size == 0;
}
8、销毁栈
void StackDestory(Stack* ps) {
if (ps->array)
{
free(ps->array);
ps->array = NULL;
ps->size = 0;
ps->capacity = 0;
}
}