You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1 KiB

2 years ago
#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;
}