当前位置:   article > 正文

数据结构初阶:栈和队列

数据结构初阶:栈和队列

栈的概念及结构

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。 进行数据插入和删除操作的一端 称为栈顶,另一端称为栈底。 栈中的数据元素遵守后进先出 LIFO Last In First Out )的原则。
压栈:栈的插入操作叫做进栈 / 压栈 / 入栈, 入数据在栈顶
出栈:栈的删除操作叫做出栈。 出数据也在栈顶

 栈的实现(数组版本)

栈的实现一般可以使用 数组或者链表实现 ,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。

Stack.h

  1. #pragma once
  2. #include<stdio.h>
  3. #include<assert.h>
  4. #include<stdlib.h>
  5. #include<stdbool.h>
  6. typedef int STDataType;
  7. // 支持动态增长的栈
  8. typedef struct Stack
  9. {
  10. int* a;
  11. int top; // 标识栈顶位置的
  12. int capacity;
  13. }ST;
  14. void STInit(ST* pst);
  15. void STDestroy(ST* pst);
  16. // 栈顶插入删除
  17. void STPush(ST* pst, STDataType x);
  18. void STPop(ST* pst);
  19. STDataType STTop(ST* pst);
  20. bool STEmpty(ST* pst);
  21. int STSize(ST* pst);

 Stack.c

注意:

解决方法一:

解决方法二:

 

 这里我们采用方法二

  1. #include"Stack.h"
  2. void STInit(ST* pst)
  3. {
  4. assert(pst);
  5. pst->a = NULL;
  6. pst->capacity = 0;
  7. pst->top = 0;
  8. }
  9. void STDestroy(ST* pst)
  10. {
  11. }
  12. // 栈顶插入删除
  13. void STPush(ST* pst, STDataType x)
  14. {
  15. assert(pst);
  16. if (pst->top == pst->capacity)
  17. {
  18. int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
  19. STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType) * newcapacity);
  20. if (tmp == NULL)
  21. {
  22. perror("realloc fail");
  23. return;
  24. }
  25. pst->a = tmp;
  26. pst->capacity = newcapacity;
  27. }
  28. pst->a[pst->top] = x;
  29. pst->top++;
  30. }
  31. void STPop(ST* pst)
  32. {
  33. assert(pst);
  34. // 不为空
  35. assert(pst->top > 0);
  36. pst->top--;
  37. }
  38. STDataType STTop(ST* pst)
  39. {
  40. assert(pst);
  41. // 不为空
  42. assert(pst->top > 0);
  43. return pst->a[pst->top - 1];
  44. }
  45. bool STEmpty(ST* pst);
  46. int STSize(ST* pst);

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

闽ICP备14008679号