当前位置:   article > 正文

实现栈的各种基本运算的算法(数据结构)

实现栈的各种基本运算的算法(数据结构)

栈的特点是先入后出,后进先出

(1)静态栈的创建

  1. //静态栈
  2. #define 10 N
  3. #define int STDataType
  4. typedef struct ST{
  5. STDataType a[N];
  6. int top;//栈顶元素
  7. }Stack;

(2)动态栈的创建(本文代码基于动态栈)

  1. //动态栈
  2. #define int STDataType
  3. typedef struct ST {
  4. STDataType* _a;
  5. int _top;//栈顶元素
  6. int _capacity;//最大容量
  7. }Stack;

(3)初始化栈

  1. //初始化栈
  2. void StackInit(Stack* pst)
  3. {
  4. assert(pst);
  5. pst->_a = NULL;
  6. pst->_top = 0;
  7. pst->_capacity = 0;
  8. }

(4)入栈

  1. //入栈
  2. void StackPush(Stack* pst, STDataType x)
  3. {
  4. assert(pst);
  5. if (pst->_top == pst->_capacity)
  6. {
  7. STDataType newcapacity = pst->_capacity == 0 ? 4 : (pst->_capacity * 2);
  8. STDataType* temp = (STDataType*)realloc(pst->_a, sizeof(STDataType) * newcapacity);
  9. if (temp == NULL)
  10. {
  11. printf("realloc fail\n");
  12. exit(-1);
  13. }
  14. pst->_a = temp;
  15. pst->_capacity = newcapacity;
  16. }
  17. pst->_a[pst->_top] = x;
  18. pst->_top++;
  19. }

(5)出栈

  1. //出栈
  2. void StackPop(Stack* pst)
  3. {
  4. assert(pst);
  5. assert(pst->_top > 0);
  6. pst->_top--;
  7. }

(6)获取栈顶元素

  1. //获取栈顶元素
  2. STDataType StackTop(Stack* pst)
  3. {
  4. assert(pst);
  5. assert(pst->_top>0);
  6. return pst->_a[pst->_top-1];
  7. }

(7)获取栈的有效个数

  1. //出栈
  2. void StackPop(Stack* pst)
  3. {
  4. assert(pst);
  5. assert(pst->_top > 0);
  6. pst->_top--;
  7. }

(8)判断栈是否为空

  1. //判断栈是否为空,是返回1,非空返回0
  2. bool StackEmpty(Stack* pst)
  3. {
  4. assert(pst);
  5. if (pst->_top == 0)
  6. return true;
  7. else
  8. return false;
  9. }

(9)打印栈

  1. //打印栈
  2. void StackPrint(Stack* pst)
  3. {
  4. while (!StackEmpty(pst))
  5. {
  6. printf("%d\n", StackTop(pst));
  7. StackPop(pst);
  8. }
  9. }

(10)销毁栈

  1. //销毁栈
  2. void StackDestory(Stack* pst)
  3. {
  4. assert(pst);
  5. free(pst->_a);
  6. pst->_a = NULL;
  7. pst->_top = pst->_capacity = 0;
  8. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号