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.

45 lines
1.2 KiB

#include <bits/stdc++.h>
using namespace std;
/*
测试样例:
+ 23 34
/ + 4 2 * 3 5
*/
// 将前缀表达式转换为后缀表达式(带空格版本)
// 判断字符是否是操作符
bool isOp(string c) {
return c == "+" || c == "-" || c == "*" || c == "/";
}
string prefixToPostfix(string s) {
stack<string> stk;
string c; // 子串
vector<string> q;
stringstream s1(s); // 构造字符串流,处理带空格的后缀表达式
while (s1 >> c) q.push_back(c); // 将每个子串抽取出来
for (int i = q.size() - 1; i >= 0; i--) {
string c = q[i];
if (isOp(c)) {
string a = stk.top();
stk.pop();
string b = stk.top();
stk.pop();
stk.push(a + " " + b + " " + c);
} else
stk.push(c); // 如果是操作数,将其转换为整数并入栈
}
return stk.top();
}
int main() {
string prefix = "/ + 4 2 * 3 5"; // / + 4 2 * 3 5 --> vector<>={/ + 4 2 * 3 5}
string postfix = prefixToPostfix(prefix);
cout << "前缀表达式: " << prefix << endl;
cout << "后缀表达式: " << postfix << endl;
return 0;
}