算法思路来自于王道的数据结构
#include <iostream>
#include <stack>
#include <map>using namespace std;
string eq;
stack<char> op;
string rst = "";
map<char, int> dict;// 获取优先级
int getPrio(char op)
{if (op == '+')return 1;if (op == '-')return 1;if (op == '*')return 2;if (op == '/')return 2;return 0;
}int main()
{cin >> eq;for (int i = 0; i < eq.length(); ++i){//是操作字符直接压入 后缀表达式中if (eq[i] >= 65 && eq[i] <= 90)rst += eq[i];else{if (op.empty() || eq[i] == '(') // 栈为空或者为'('直接入栈(优先判断栈是否为空)op.push(eq[i]);else if (eq[i] == ')') // 如果是右括号执行相应逻辑{while (op.top() != '('){char ch = op.top();rst += ch;op.pop();}op.pop(); // 弹出'('}else{while (getPrio(eq[i]) <= getPrio(op.top())) // 当前符号优先级大于栈顶符号{rst += op.top();op.pop();if (op.empty())break;}op.push(eq[i]); // 压入当前符号}}}while (!op.empty()){char ch = op.top();rst += ch;op.pop();}cout << rst;return 0;
}