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.

67 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/38-5)+4)
24 9 6 38 / + 5 - * 4 +
*/
unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 运算符级别表
string s; // 源串
string t; // 目标串
stack<char> 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;
}