#include <cstdio>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
const int N = 100010;
char str[N];
stack<int> num;
stack<char> op;
unordered_map<char, int> pr({{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}});
void eval()
{
int b = num.top(); num.pop();
int a = num.top(); num.pop();
char c = op.top(); op.pop();
int x = 0;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
scanf("%s", str);
for (int i = 0; i < strlen(str); i++) {
char c = str[i];
if (c == '(') op.push(c);
else if (c == ')') {
while (op.top() != '(') eval();
op.pop();
} else if (isdigit(c)) {
int x = 0, j = i;
while (j < strlen(str) && isdigit(str[j])) x = x * 10 + str[j++] - '0';
i = j - 1;
num.push(x);
} else {
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
op.push(c);
}
}
while (op.size()) eval();
printf("%d", num.top());
return 0;
}
标签:中缀,int,top,else,num,str,求值,表达式,op
From: https://www.cnblogs.com/cong0221/p/17155596.html