WHCSRL 技术网

链栈(C语言实现)_Mr

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<stdbool.h>
  4. typedef int DataType;
  5. typedef struct SNode
  6. {
  7. DataType data;
  8. struct SNode * next;
  9. }*LinkStack;
  10. bool Init_Stack(LinkStack * Top); // 栈初始化(不带头结点)
  11. bool Push_Stack(LinkStack * Top, DataType x); // 入栈
  12. bool Pop_Stack(LinkStack * Top, DataType * x); // 出栈
  13. int GetTop_Stack(LinkStack Top); // 获取栈顶元素
  14. bool Destroy_Stack(LinkStack * Top); // 销毁栈
  15. bool Traverse_Stack(LinkStack Top); // 遍历栈
  16. bool Empty_Stack(LinkStack Top); // 判栈空
  17. int main()
  18. {
  19. DataType x;
  20. LinkStack S;
  21. if(Init_Stack(&S))
  22. printf("链栈初始化成功! ");
  23. else
  24. printf("链栈初始化失败! ");
  25. Push_Stack(&S,1);
  26. Push_Stack(&S,4);
  27. Push_Stack(&S,7);
  28. Push_Stack(&S,2);
  29. Push_Stack(&S,5);
  30. Push_Stack(&S,8);
  31. Push_Stack(&S,3);
  32. Push_Stack(&S,6);
  33. Push_Stack(&S,9);
  34. printf("遍历链栈:");
  35. Traverse_Stack(S);
  36. printf(" ");
  37. printf("栈顶元素:%%d ",GetTop_Stack(S));
  38. if(Pop_Stack(&S, &x))
  39. {
  40. printf("出栈成功! ");
  41. printf("您出栈的元素:%%d ",x);
  42. }
  43. else
  44. printf("出栈失败! ");
  45. printf("遍历链栈:");
  46. Traverse_Stack(S);
  47. printf(" ");
  48. if(Destroy_Stack(&S))
  49. printf("销毁成功! ");
  50. else
  51. printf("销毁失败! ");
  52. printf("遍历链栈:");
  53. Traverse_Stack(S);
  54. return 0;
  55. }
  56. // 注意防止产生空指针
  57. bool Init_Stack(LinkStack * Top)
  58. {
  59. *Top = NULL; // 空栈时,栈顶指针指向空
  60. return true;
  61. }
  62. // 注意防止产生空指针
  63. bool Push_Stack(LinkStack * Top, DataType x)
  64. {
  65. printf("入栈元素:%%d ",x);
  66. LinkStack p = (LinkStack)malloc(sizeof(struct SNode));
  67. if(!p)
  68. {
  69. printf("申请空间失败! ");
  70. exit(-1);
  71. }
  72. p->data = x;
  73. p->next = *Top;
  74. *Top = p;
  75. return true;
  76. }
  77. // 注意防止产生空指针
  78. bool Pop_Stack(LinkStack * Top, DataType * x)
  79. {
  80. if(Empty_Stack(*Top))
  81. return false;
  82. LinkStack p = *Top;
  83. *x = p->data;
  84. *Top = p->next;
  85. free(p);
  86. p = NULL;
  87. return true;
  88. }
  89. int GetTop_Stack(LinkStack Top)
  90. {
  91. if(Empty_Stack(Top))
  92. return false;
  93. return Top->data;
  94. }
  95. // 注意防止产生空指针
  96. bool Destroy_Stack(LinkStack * Top)
  97. {
  98. LinkStack p = *Top;
  99. while(*Top)
  100. {
  101. p = p->next;
  102. free(*Top);
  103. *Top = p;
  104. }
  105. return true;
  106. }
  107. bool Traverse_Stack(LinkStack Top)
  108. {
  109. LinkStack p = Top;
  110. while(p)
  111. {
  112. printf("%%3d",p->data);
  113. p = p->next;
  114. }
  115. return true;
  116. }
  117. bool Empty_Stack(LinkStack Top)
  118. {
  119. if(Top==NULL)
  120. return true;
  121. else
  122. return false;
  123. }

推荐阅读