中缀表达式转后缀表达式
#include <iostream> #include <map> #include <stack> #include <string> using namespace std; map<char,int> priorityIn{ {'+',3}, {'-',3}, {'*',5}, {'/',5}, {'(',1}, {')',6} }; map<char,int> priorityOut{ {'+',2}, {'-',2}, {'*',4}, {'/',4}, {'(',6}, {')',1} }; int main() { string in; stack<char> op; char c; map<char, int>::iterator iter; cin >> in; for (int i = 0; i < in.length(); ++i) { c = in[i]; iter = priorityIn.find(c); if (iter != priorityIn.end()) { if (op.empty()) op.push(c); else { if (priorityOut.at(c) >= priorityIn.at(op.top())) op.push(c); else { while(!op.empty() && priorityOut.at(c) < priorityIn.at(op.top())) { cout << op.top(); op.pop(); } if (c == ')') op.pop(); else op.push(c); } } } else cout << c; } while(!op.empty()) { cout << op.top(); op.pop(); } return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步