四则运算表达式求值 - 逆波兰表示法
逆波兰表示法是栈结构的典型应用。
在逆波兰表示法中,无论是“把中缀表达式转化成后缀表达式”,还是“计算后缀表达式”,都需要用栈作为工具。
所以我写了一个简单的表达式转换程序试了下……(仅支持个位数加减法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include <iostream> #include <string> #include <stack> #include <cctype> using namespace std;
inline unsigned short prior(char c) { switch (c) { case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } }
void convert_expression(string& a, string& c) { stack<char> b;
for (int i = 0; i < a.length(); ++i) { if (('0'<=a[i] && a[i]<='9')) { c.push_back(a[i]); continue; } else if (a[i] == '(') { b.push(a[i]); } else if (a[i]==')') { while (b.top() != '(') { c.push_back(b.top()); b.pop(); } b.pop(); continue; } else if (prior(a[i])) { while (!b.empty() && prior(a[i]) <= prior(b.top())) { c.push_back(b.top()); b.pop(); } b.push(a[i]); } else { cout << "Please check your expression." << endl; } } while (!b.empty()) { c.push_back(b.top()); b.pop(); } }
int main(void) { string expression; cin >> expression; string postfix_expression; convert_expression(expression, postfix_expression); cout << postfix_expression << endl; }
|