栈
栈是一个带有限制性的表,它只能在栈顶插入和删除,栈最基本的操作就是push(入栈)和pop(出栈),栈又叫做LIFO表(Last in,First out list)。由于栈是表结构,所以可以用数组或者链表实现其结构。
栈的数组实现
栈的结构:
typedef int DataType;
typedef struct Stack {
DataType* a;//定义一个数组来存储数据
int top;//记录栈顶位置
int capacity;//控制栈的大小
}ST;
栈的基本操作声明:
void StackInit(ST* ps);//初始化栈
void StackDestory(ST* ps);//销毁栈
void StackPush(ST* ps, STDataType x);//Push数据进入栈中
void StackPop(ST* ps);//栈顶数据出栈
STDataType StackTop(ST* ps);//寻找栈顶元素
int StackSize(ST* ps);//栈数据数量
bool StackEmpty(ST* ps);//栈是否为空
栈初始化和销毁函数:
void StackInit(ST* ps) {
assert(ps);
ps->a = NULL;
ps->top = 0;//top在数据的下一个位置
ps->capacity = 0;
}//初始化函数
void StackDestory(ST* ps) {
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}//销毁栈
出栈和入栈函数:
void StackPush(ST* ps, STDataType x) {
assert(ps);//检查是否为空
if (ps->top == ps->capacity) {//如果栈顶位置和容量相同需要扩容
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
ps->a = realloc(ps->a, newCapacity * sizeof(STDataType));
if (ps->a == NULL) {
printf("realloc fail\n");
exit(-1);
}
ps->capacity = newCapacity;
}
ps->a[ps->top] = x;//插入数据
ps->top++;//top++
}
void StackPop(ST* ps) {
assert(ps);
assert(ps->top > 0);
--ps->top;
}//pop直接top--
查询栈是否为空:
bool StackEmpty(ST* ps) {
assert(ps);
return ps->top == 0;
}
查询栈内元素和栈顶元素:
DataType StackTop(ST* ps) {
assert(ps);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
测试函数:
#include"Stack.h"
void Test1() {
ST s;
StackInit(&s);
StackPush(&s, 1);
StackPush(&s, 2);
while (!StackEmpty(&s)) {
STDataType a = StackTop(&s);
printf("%d ", a);
StackPop(&s);
}
printf("\n");
}
int main() {
Test1();
return 0;
}