运用栈实现表达式求值(+,-,*,/运算)
1 #include <iostream> 2 #include <string> 3 #include <cassert> 4 #include <iomanip> 5 using namespace std; 6 template<typename Type> class Stack { 7 private: 8 Type *elements; 9 int max_size, top_index; 10 public: 11 Stack(int length_input) { 12 elements = new Type[length_input]; 13 max_size = length_input; 14 top_index = -1; 15 } 16 ~Stack() { 17 delete[] elements; 18 } 19 bool push(const Type &element) { 20 if (top_index >= max_size - 1) { 21 return false; 22 } 23 top_index++; 24 elements[top_index] = element; 25 return true; 26 } 27 bool pop() { 28 if (top_index < 0) { 29 return false; 30 } 31 top_index--; 32 return true; 33 } 34 Type top() { 35 assert(top_index >= 0); 36 return elements[top_index]; 37 } 38 bool empty() { 39 return top_index < 0; 40 } 41 }; 42 43 static char pre[128] = { 0 }; 44 45 void setpre() 46 { 47 pre['+'] = 1; 48 pre['-'] = 1; 49 pre['*'] = 2; 50 pre['/'] = 2; 51 } 52 53 bool precede(char op1, char op2) { 54 return pre[op1] > pre[op2] ? true : false; 55 } 56 double operate(char theta, double a, double b) { 57 switch (theta) { 58 case '-': return b - a; break; 59 case '+': return a + b; break; 60 case '*': return a * b; break; 61 case '/': return (b * 1.0) / a; break; 62 } 63 } 64 void calc(Stack<double> &numbers, Stack<char> &operators) { 65 double a = numbers.top(); 66 numbers.pop(); 67 double b = numbers.top(); 68 numbers.pop(); 69 numbers.push(operate(operators.top(), a, b)); 70 operators.pop(); 71 } 72 int main() { 73 int n; 74 setpre(); 75 cin >> n; 76 Stack<double> numbers(n); 77 Stack<char> operators(n); 78 string buffer; 79 cin >> buffer; 80 int i = 0; 81 while (i < n) { 82 if (isdigit(buffer[i])) { 83 numbers.push(buffer[i] - '0'); 84 i++; 85 } else { 86 if (operators.empty() || precede(buffer[i], operators.top())) { 87 operators.push(buffer[i]); 88 i++; 89 } else { 90 calc(numbers, operators); 91 } 92 } 93 } 94 while (!operators.empty()) { 95 calc(numbers, operators); 96 } 97 cout << fixed << setprecision(3) << numbers.top() << endl; 98 return 0; 99 }