c++:棧的應用之表達式求值

 Stack.hpp

  1. #pragma once


  2. template <class T>

  3. class Stack{

  4. private:

  5. T* _array;

  6. size_t _capacity;

  7. int _topindex;

  8. public:

  9. Stack()          //構造函數

  10. :_array(0)

  11. , _capacity(0)

  12. , _topindex(-1)

  13. {}

  14. void Push(const T& x){                         //入棧操作

  15. if (_topindex + 1 == _capacity){

  16. _capacity = 2 * _capacity + 3;

  17. T* tmp = new T[_capacity];

  18. if (tmp == NULL){

  19. cout << "failed new" << endl;

  20. exit(-1);

  21. }

  22. memcpy(tmp, _array, sizeof(T) * (_topindex + 1));

  23. delete _array;

  24. _array = tmp;

  25. }

  26. _array[++_topindex] = x;

  27. }

  28. void Pop(){                                      //出棧

  29. if (_topindex > -1){

  30. //cout << _array[_topindex] << endl;

  31. _topindex--;

  32. }

  33. bool empty(){                  //清空

  34. return _topindex = -1;

  35. }

  36. const T& top(){                             //取棧頂元素

  37. //cout << _array[_topindex] << endl;

  38. return _array[_topindex];

  39. }

  40. };


  41. main.cpp

  42. #include<iostream>

  43. #include<string>

  44. #include"Stack.hpp"

  45. using namespace std;


  46. enum Type{

  47. ADD,

  48. SUB,

  49. MUL,

  50. DIV,

  51. OP_NUM,

  52. };


  53. struct Cell{

  54. Type _type;

  55. int num;

  56. };


  57. Cell RPNExp[] = {

  58. OP_NUM, 12,

  59. OP_NUM, 3,

  60. OP_NUM, 4,

  61. ADD, 1,

  62. MUL, 1,

  63. OP_NUM, 6,

  64. SUB, 1,

  65. OP_NUM, 8,

  66. OP_NUM, 2,

  67. DIV, 1,

  68. ADD, 1,

  69. };


  70. int main(){   

  71. Stack<int> s2;    

  72. int i = 0;

  73. for (int i = 0; i < sizeof(RPNExp) / sizeof(RPNExp[0]);i++){  //取出元素

  74.     int left, right;             //兩個操作數

  75. switch (RPNExp[i]._type){        //將棧中數據出棧

  76. case ADD:                         //如果是加號,取兩個操作數

  77. left = s2.top();

  78. s2.Pop();

  79. right = s2.top();

  80. s2.Pop();

  81. s2.Push(left + right);         //新的值入棧

  82. break;

  83. case SUB:                       //如果是減號,取兩個操作數

  84. left = s2.top();

  85. s2.Pop();

  86. right = s2.top();

  87. s2.Pop();

  88. s2.Push(right - left);

  89. break;

  90. case MUL:                         //如果是乘號,取兩個操作數

  91. left = s2.top();

  92. s2.Pop();

  93. right = s2.top();

  94. s2.Pop();

  95. s2.Push(left * right);

  96. break;

  97. case DIV:                        //如果是除號,取兩個操作數

  98. left = s2.top();

  99. s2.Pop();

  100. right = s2.top();

  101. s2.Pop();

  102. s2.Push(right / left);

  103. break;

  104. case OP_NUM:                     //如果數字,入棧

  105. s2.Push(RPNExp[i].num);

  106. break;

  107. default:

  108. return -1;

  109. }

  110. }

  111. cout << s2.top() << endl;

  112. return 0;

  113. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章