当前位置:   article > 正文

数据结构栈创建。_数据结构实现栈的创建

数据结构实现栈的创建

注意在声明完指针之后需要初始化。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define STACK_SIZE 20
  4. #define APPEND_SIZE 20
  5. struct stack_t
  6. {
  7. int* base;
  8. int* top;
  9. int stacksize;
  10. };
  11. //压入数据
  12. void Push(stack_t *S, int data)
  13. {
  14. //满了就扩充
  15. if ((S->top - S->base) >= S->stacksize)
  16. {
  17. S->base = (int*)realloc(S->base, (STACK_SIZE + APPEND_SIZE) * sizeof(int));
  18. }
  19. *S->top = data;
  20. S->top++ ;
  21. }
  22. int Pop(stack_t *S, int data)
  23. {
  24. if (S->base == S->top)
  25. {
  26. exit(1);
  27. }
  28. data = *--S->top;
  29. return data;
  30. }
  31. int main()
  32. {
  33. stack_t* my_stack = new stack_t;
  34. my_stack->base = (int*)malloc(STACK_SIZE * sizeof(int));
  35. //my_stack->base = new int[STACK_SIZE];
  36. if (!my_stack->base)
  37. exit(1);
  38. my_stack->top = my_stack->base;
  39. my_stack->stacksize = STACK_SIZE;
  40. Push(my_stack, 2);
  41. Push(my_stack, 3);
  42. delete[] my_stack;
  43. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/840407
推荐阅读
相关标签
  

闽ICP备14008679号