示例:9+(3-1)*3+10/2

#include<map>
#include<stack>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
map
<char, int> p; struct Node { double num; char op; bool flag; }; stack<Node> s; queue<Node> q; void midtoback(string str) { Node temp; for (int i = 0; i < str.length();) { if (str[i] == '(') { temp.flag = false; temp.op = str[i]; s.push(temp); i++; } else if (str[i] == ')') { while (!s.empty() && s.top().op != '(') { q.push(s.top()); s.pop(); } s.pop(); i++; } else if(str[i]>='0'&&str[i]<='9') { temp.flag = true; temp.num = str[i] - '0'; i++; while (i < str.length() && str[i] >= '0' && str[i] <= '9') { temp.num = temp.num * 10 + (str[i] - '0'); i++; } q.push(temp); } else { temp.flag = false; while (!s.empty() && p[s.top().op] >= p[str[i]]) { q.push(s.top()); s.pop(); } temp.op = str[i]; s.push(temp); i++; } } while (!s.empty()) { q.push(s.top()); s.pop(); } } int main() { Node cur; string str; p['+'] = p['-'] = 1; p['*'] = p['/'] = 2; cin >> str; midtoback(str); while (!q.empty()) { cur = q.front(); if (cur.flag == true) cout << cur.num << " "; else cout << cur.op << " "; q.pop(); } return 0; }
01-25 11:27