#include using namespace std; // 中缀表达式转后缀表达式 /* 测试用例1: a+b*c+(d*e+f)*g 答案: abc*+de*f+g*+ 测试用例2: (6+3*(7-4))-8/2 答案: 6 3 7 4 - * + 8 2 / - 测试用例3: (24*(9+6/38-5)+4) 答案: 24 9 6 38 / + 5 - * 4 + */ unordered_map h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 运算符级别表 string s; // 源串 string t; // 目标串 stack stk; // 利用一个栈,完成中缀表达式转后缀表达式 int main() { cin >> s; for (int i = 0; i < s.size(); i++) { // ①数字 if (isdigit(s[i])) { int x = 0; while (i < s.size() && isdigit(s[i])) { x = x * 10 + s[i] - '0'; i++; } i--; // 走多了才能停止掉上面的while,需要回退一下 t.append(to_string(x)); } else if (isalpha(s[i])) // ②字符,比如a,b,c t.push_back(s[i]); else if (s[i] == '(') // ③左括号 stk.push(s[i]); // 左括号入栈 else if (s[i] == ')') { // ④右括号 while (stk.top() != '(') { // 让栈中元素(也就是+-*/和左括号)一直出栈,直到匹配的左括号出栈 t.push_back(stk.top()); stk.pop(); } stk.pop(); // 左括号也需要出栈 } else { // ⑤操作符 +-*/ while (stk.size() && h[s[i]] <= h[stk.top()]) { // 哪个操作符优先级高就先输出谁 t.push_back(stk.top()); stk.pop(); } stk.push(s[i]); // 将自己入栈 } } // 当栈不为空时,全部输出 while (stk.size()) { t.push_back(stk.top()); stk.pop(); } // printf("%s", t.c_str()); cout << t << endl; return 0; }