中缀转后缀再求值
作者:
zzu
,
2024-03-31 21:05:33
,
所有人可见
,
阅读 3
#include <iostream>
#include <string>
#include <stack>
#include <unordered_map>
#include <vector>
using namespace std;
string s;
stack<char> op;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};//优先级
vector<string> r;//存储的是中转后的表达式比如 2 2 *
int main() {
cin >> s;
//中转后缀
for (int i = 0; i < s.size(); i ++) {
if (isdigit(s[i])) {
int j = i, x = 0;
while (j < s.size() && isdigit(s[j])) x = x * 10 + (s[j ++] - '0');
i = j - 1;
r.push_back(to_string(x));//把对应的数字转换成字符串
}
else if (s[i] == '(') {
op.push(s[i]);
}
else if (s[i] == ')')
{
while (op.top() != '(') {
r.push_back(string{op.top()});//强制类型转换op.top()是char类型=>string
op.pop();
}
op.pop();
}
else
{
while (op.size() && pr[op.top()] >= pr[s[i]]) //注意首先要判断栈是否存在
{
r.push_back(string{op.top()});
op.pop();
}
op.push(s[i]);
}
}
while (op.size()) {
r.push_back(string{op.top()});
op.pop();
}
stack<int> num;
for (int i = 0; i < r.size(); i ++) {
auto c = r[i];
if (isdigit(c[0])) { // 这里c是一个字符串比如222,isdigit是判断一个字符,所以s[0];
num.push(stoi(c));//字符转数字的强制转换
}
else {
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
int k = 0;
if (c == "+") { // 注意这里c是字符串string类型的所以用"
k = a + b;
} else if (c == "-") {
k = a - b;
} else if (c == "*") {
k = a * b;
} else if (c == "/") {
k = a / b;
}
nums.push(k);
}
}
cout << nums.top() << endl;
return 0;
}