马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
目录
栈
概念与布局
栈底层布局选型
数组
链表
使用数组实现栈
编辑
初始化栈
判断栈空
入栈
出栈
取栈顶元素
栈的元素个数
烧毁
栈
概念与布局
栈是一种特殊的线性表,它只答应在固定的一端举行插入和删除元素利用。举行数据插入和删除利用的一端称为栈顶,另一端称为栈底。栈中的数据依照先辈后出的原则。
压栈:栈的插入利用叫做压栈/入栈/进栈。
出栈:栈的删除利用叫做出栈。
出数据和入数据都在栈顶。
栈底层布局选型
数组
链表
那么对于数组和链表我们选择哪个比力好呢?
答案是数组。由于链表固然动态性更强,但是每个利用都必要动态分配结点,内存开销比力大,且频仍分配/释放可能引发内存碎片。而数组尾插尾删的服从更高。
使用数组实现栈
我们就根据次序表的布局来模拟一遍栈的布局。
- typedef int STDataType;
- typedef struct stack
- {
- STDataType* arr;
- int top;
- int capacity;
- }ST;
复制代码 初始化栈
- void STInit(ST* ps)
- {
- assert(ps);
- ps->arr = NULL;
- ps->top = ps->capacity = 0;
- }
复制代码 判断栈空
- bool STEmpty(ST* ps)
- {
- assert(ps);
- return ps->top == 0;
- }
复制代码 入栈
- void STCheck(ST* ps)
- {
- if (ps->top == ps->capacity)
- {
- int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
- STDataType* tmp = (STDataType*)realloc(ps->arr, newcapacity * sizeof(STDataType));
- if (tmp == NULL)
- {
- perror("realloc failed!");
- exit(1);
- }
- else
- {
- ps->arr = tmp;
- ps->capacity = newcapacity;
- }
- }
- }
复制代码- void STPush(ST* ps, STDataType x)
- {
- assert(ps);
- STCheck(ps);
- ps->arr[ps->top++] = x;
- }
复制代码 出栈
- void STPop(ST* ps)
- {
- assert(ps && ps->arr && !STEmpty(ps));
- ps->top--;
- }
复制代码 注意:删除的空间不能free掉,由于动态开发的空间不能局部释放。
取栈顶元素
- STDataType STTop(ST* ps)
- {
- assert(ps && ps->arr && !STEmpty(ps));
- return ps->arr[ps->top-1];
- }
复制代码 栈的元素个数
- int STSize(ST* ps)
- {
- assert(ps);
- return ps->top;
- }
复制代码 烧毁
- void STDestroy(ST* ps)
- {
- assert(ps);
- free(ps->arr);
- ps->arr = NULL;
- ps->top = ps->capacity = 0;
- }
复制代码
|