赞
踩
今天我们讲解新的领域——栈。
栈:一种特殊的线性表,其允许在固定的一段进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In Fist Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
栈就相当于弹匣,后放入放入的子弹会先射出去,当我们将子弹从弹匣中取出来时,同样也只能从弹匣顶部(这里就相当于栈顶)一颗一颗取出子弹。
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价更小。
- #pragma once
- #include<stdio.h>
- #include<assert.h>
- #include<stdlib.h>
- #include<stdbool.h>
- typedef int STDataType;
- struct Stack
- {
- STDataType* a;
- int top;
- int capacity;
- };
- typedef struct Stack ST;
- void STInit(ST* ps);//栈的初始化
- void STDestroy(ST* ps);//栈的销毁
-
- void STPush(ST*PS,STDataType x);//入栈
- void STPop(ST* ps);//出栈
-
- STDataType STTop(ST* ps);//取栈顶的数据
-
- bool STEmpty(ST*ps);//判空
-
- int STSize(ST* PS);//获取数据个数
这里是不是和我们之前实现的顺序表相似?没错,他的实现机理与顺序表说一样的。有兴趣的小伙伴,可以了解一下,下面是链接: 写文章-CSDN创作中心。
- #include"Stack.h"
- void STInit(ST *ps)//栈的初始化
- {
- assert(ps);
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
- void STDestroy(ST* ps)//栈的销毁
- {
- assert(ps);
- free(ps->a);
- ps->a = NULL;
- ps->top = ps->capacity = 0;
- }
- void STPush(ST* ps, STDataType x)//入栈
- {
- assert(ps);
- if (ps->capacity == ps->top)
- {
- int newcapacity = ps->capacity == 0 ? 6 : ps->capacity*2;
- STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
- if (tmp == NULL)
- {
- perror("realloc fail!");
- return;
- }
- ps->a = tmp;
- ps->capacity = newcapacity;
- }
- ps->a[ps->top] = x;
- ps->top++;
- }
- void STPop(ST* ps)//删除栈顶元素
- {
- assert(ps);
- assert(ps->a);
- ps->top--;
- }
- STDataType STTop(ST* ps)//取出栈顶元素
- {
- assert(ps);
- assert(ps->top >= 0);
- return ps->a[ps->top-1];
- }
- bool STEmpty(ST* ps)//判断栈内元素是否为空
- {
- asssert(ps);
- if (ps->top == 0)
- return 1;
- return 0;
- }
- int STSize(ST* ps)//获取数据个数
- {
- assert(ps);
- return ps->top ;
- }
- #include"Stack.h"
- void test01()
- {
- ST s;
- STInit(&s);
- STPush(&s,1);
- STPush(&s, 2);
- STPush(&s, 3);
- STPush(&s, 4);
- /*STPop(&s);
- STPop(&s);
- STPop(&s);
- STPop(&s);*/
- while (s.top)
- {
- printf("%d\n", STTop(&s));
- STPop(&s);
- }
- STDestroy(&s);
- }
- int main()
- {
- test01();
- return 0;
- }
上面的test.c是我为了测试代码是能正常运行写的。大家看看就行。
栈的实现分享就到这了,如果对大家有所帮助的话,求一个三连。谢谢啦。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。