1.中缀转后缀的要点 (1)遇到数字需要直接输出,但是有时数字可能不只是一个个位数,因此需要遍历表达式,获取该值。 (2)如果运算符栈为空,如果遇到运算符,直接入栈。 (3)如果遇到"(",直接入栈。 (4)如果遇到")",连续出栈,一直到栈顶元素是"(",然后出栈"("。 (5)如果遇到运算符且运算符栈不为空,此时需要比较当前运算符和栈顶运算符的优先级。分两种情况:1.当前运算符优先级大于栈顶运算符优先级,直接入栈。2.当前运算符优先小于栈顶运算符优先级,需要一直出栈,直到栈顶运算符优先小于当前运算符,将当前运算符入栈。
2.代码实现
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
#define ERROR 0x3f3f
string cto_string(char c) {
stringstream stream;
stream << c;
return stream.str();
}
int cmp(char a, char b) {
if (a=='+') {
if (b == '-' || b == '+') return 0;
else if (b == '*' || b == '/') return -1;
else if (b == '(') return 1;
} else if (a == '-') {
if (b == '-' || b == '+') return 0;
else if (b == '*' || b == '/') return -1;
else if (b == '(') return 1;
} else if (a == '*') {
if (b == '*' || b == '/') return 0;
else if(b == '+' || b == '-' || b == '(') return 1;
} else if (a == '/') {
if (b == '*' || b == '/') return 0;
else if(b == '+' || b == '-' || b == '(') return 1;
} else {
cout << "invalid sign" << endl;
return ERROR;
}
}
vector<string> res;
vector<string> InfixToSuffix(string infix) {
stack<char> st;
int i = 0;
while (i < infix.length()) {
if (infix[i] == '(') {
st.push(infix[i]);
i ++;
} else if (infix[i] == ')') {
while (!st.empty()) {
char op = st.top();st.pop();
if (op == '(') break;
else res.push_back(cto_string(op));
i ++;
}
} else if (isdigit(infix[i])) {
int n = infix[i ++] - '0';
while (i < infix.length() && isdigit(infix[i])) {
n = n * 10 + (infix[i ++] - '0');
}
res.push_back(to_string(n));
} else {
if (st.empty()) st.push(infix[i]);
else {
if (cmp(infix[i], st.top()) > 0) st.push(infix[i]);
else if (cmp(infix[i], st.top()) <= 0) {
while (!st.empty()) {
char op = st.top();st.pop();
res.push_back(cto_string(op));
if (cmp(infix[i], op) > 0) break;
}
st.push(infix[i]);
}
}
i ++;
}
}
while (!st.empty()) {
res.push_back(cto_string(st.top())); st.pop();
}
return res;
}
//计算后缀表达式的值
int calculate(vector<string>& a) {
stack<int> st;
for (auto x : a) {
if (x == "+") {
int a = st.top();st.pop();
int b = st.top();st.pop();
st.push(b + a);
}
else if (x == "-") {
int a = st.top();st.pop();
int b = st.top();st.pop();
st.push(b - a);
}
else if (x == "*") {
int a = st.top();st.pop();
int b = st.top();st.pop();
st.push(b * a);
}
else if (x == "/") {
int a = st.top();st.pop();
int b = st.top();st.pop();
st.push(b / a);
}
else {
st.push(stoi(x));
}
}
return st.top();
}
void print(string a) {cout << a << " ";}
int main() {;
string s;
cin >> s;
vector<string> t = InfixToSuffix(s);
for_each(t.begin(), t.end(), print);cout << endl;
int ans = calculate(t);
cout << ans << endl;
return 0;
}