Stack.hpp

  1. #pragma once


  2. template

  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

  43. #include

  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 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. }