当前位置:   article > 正文

【数据结构】栈

【数据结构】栈

stack.h

  1. #pragma once
  2. #include<stdlib.h>
  3. #include<assert.h>
  4. #include<stdbool.h>
  5. typedef int STDataType;
  6. typedef struct Stack
  7. {
  8. STDataType* a;
  9. int capacity;
  10. int top;
  11. } Stack;
  12. Stack* STCreate();
  13. void STDestroy(Stack* st);
  14. void STPush(Stack* st, STDataType x);
  15. STDataType STPop(Stack* st);
  16. STDataType STTop(Stack* st);
  17. int STSize(Stack* st);
  18. bool STEmpty(Stack* st);

stack.c

  1. #include"Stack.h"
  2. Stack* STCreate()
  3. {
  4. Stack* st = (Stack*)malloc(sizeof(Stack));
  5. if (NULL == st)
  6. {
  7. perror("malloc failed");
  8. exit(-1);
  9. }
  10. st->a = NULL;
  11. st->capacity = st->top = 0;
  12. return st;
  13. }
  14. void STDestroy(Stack* st)
  15. {
  16. assert(st);
  17. free(st->a);
  18. st->a = NULL;
  19. st->capacity = st->top = 0;
  20. free(st);
  21. }
  22. void STPush(Stack* st, STDataType x)
  23. {
  24. assert(st);
  25. if (st->capacity == st->top)
  26. {
  27. int newcapacity = st->capacity == 0 ? 4 : st->capacity * 2;
  28. STDataType* temp = (STDataType*)realloc(st->a, sizeof(STDataType) * newcapacity);
  29. if (NULL == temp)
  30. {
  31. perror("realloc failed");
  32. exit(-1);
  33. }
  34. st->a = temp;
  35. st->capacity = newcapacity;
  36. }
  37. st->a[st->top] = x;
  38. ++st->top;
  39. }
  40. STDataType STPop(Stack* st)
  41. {
  42. assert(st);
  43. assert(st->top);
  44. STDataType ret = STTop(st);
  45. --st->top;
  46. return ret;
  47. }
  48. STDataType STTop(Stack* st)
  49. {
  50. assert(st);
  51. assert(st->top);
  52. return st->a[st->top - 1];
  53. }
  54. int STSize(Stack* st)
  55. {
  56. return st->top;
  57. }
  58. bool STEmpty(Stack* st)
  59. {
  60. return st->top == 0;
  61. }

test.c

  1. #include <stdio.h>
  2. #include"Stack.h"
  3. static void STPrint(Stack* st)
  4. {
  5. while (!STEmpty(st))
  6. printf("%d-", STPop(st));
  7. printf("\n");
  8. }
  9. void test1()
  10. {
  11. Stack* st1 = STCreate();
  12. STPush(st1, 4);
  13. STPush(st1, 3);
  14. STPush(st1, 2);
  15. STPush(st1, 1);
  16. STPop(st1);
  17. printf("top = %d\n", STTop(st1));
  18. printf("size = %d\n", STSize(st1));
  19. STPrint(st1);
  20. STDestroy(st1);
  21. }
  22. int main()
  23. {
  24. test1();
  25. return 0;
  26. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/762415
推荐阅读
相关标签
  

闽ICP备14008679号