Files
python/TangDou/CSP-J/J2_2020/ZhuanTi_BiaoDaShi/ToPostFix/InFixToPostfix.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

78 lines
2.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
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/3-5)+4)
答案:
24 9 6 3 / + 5 - * 4 +
测试用例4:
2*3*2+5/3
*/
unordered_map<char, int> g{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 操作符优化级
string t; // 结果串
stack<char> stk; // 栈
// 中缀转后缀
string infixToPostfix(string 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--;
t += to_string(x), t += ' ';
} else if (isalpha(s[i])) // ②字符,比如a,b,c
t += s[i], t += ' ';
else if (s[i] == '(') // ③左括号
stk.push(s[i]); // 左括号入栈
else if (s[i] == ')') { // ④右括号
while (stk.top() != '(') { // 让栈中元素(也就是+-*/和左括号)一直出栈,直到匹配的左括号出栈
t += stk.top(), t += ' ';
stk.pop();
}
stk.pop(); // 左括号也需要出栈
} else {
// ⑤操作符 +-*/
while (stk.size() && g[s[i]] <= g[stk.top()]) {
t += stk.top(), t += ' ';
stk.pop();
}
stk.push(s[i]); // 将自己入栈
}
}
// 当栈不为空时,全部输出
while (stk.size()) {
t += stk.top(), t += ' ';
stk.pop();
}
return t;
}
int main() {
string infix = "(24*(9+6/3-5)+4)";
string postfix = infixToPostfix(infix);
cout << "中缀表达式: " << infix << endl;
cout << "后缀表达式: " << postfix << endl;
return 0;
}