【数据结构】顺序栈的表示和实现

蔚落 2021-11-29 05:48 377阅读 0赞
  1. #include<iostream>
  2. using namespace std;
  3. const int MAXSIZE = 100;
  4. typedef struct Stack{
  5. int data[MAXSIZE];
  6. int top;
  7. }Stack;
  8. void InitStack(Stack &S) {
  9. S.top = -1;
  10. }
  11. bool StackEmpty(Stack S) {
  12. if (S.top == -1)
  13. return true;
  14. return false;
  15. }
  16. bool Push(Stack &S, int data) {
  17. if (S.top == MAXSIZE-1)
  18. return false;
  19. S.data[++S.top] = data;
  20. return true;
  21. }
  22. bool Pop(Stack &S, int &data) {
  23. if (S.top == -1)
  24. return false;
  25. data = S.data[S.top--];
  26. return true;
  27. }
  28. bool GetTop(Stack S, int &data) {
  29. if (S.top == -1)
  30. return false;
  31. data = S.data[S.top];
  32. return true;
  33. }
  34. void PrintStack(Stack S) {
  35. if (StackEmpty(S)) {
  36. cout<<"Stack is empty"<<endl;
  37. return;
  38. }
  39. cout<<"Stack :";
  40. while (S.top != -1) {
  41. cout<<S.data[S.top]<<" ";
  42. S.top--;
  43. }
  44. cout<<endl<<endl;
  45. }
  46. int main() {
  47. Stack S;
  48. InitStack(S);
  49. cout<<"Init Stack"<<endl;
  50. for (int i=1; i<9; i++)
  51. Push(S, i*i);
  52. PrintStack(S);
  53. while (!StackEmpty(S)) {
  54. int top;
  55. Pop(S, top);
  56. cout<<"After pop "<<top<<endl;
  57. PrintStack(S);
  58. }
  59. return 0;
  60. }
  61. // 测试结果
  62. Init Stack
  63. Stack :64 49 36 25 16 9 4 1
  64. After pop 64
  65. Stack :49 36 25 16 9 4 1
  66. After pop 49
  67. Stack :36 25 16 9 4 1
  68. After pop 36
  69. Stack :25 16 9 4 1
  70. After pop 25
  71. Stack :16 9 4 1
  72. After pop 16
  73. Stack :9 4 1
  74. After pop 9
  75. Stack :4 1
  76. After pop 4
  77. Stack :1
  78. After pop 1
  79. Stack is empty

发表评论

表情:
评论列表 (有 0 条评论,377人围观)

还没有评论,来说两句吧...

相关阅读