栈-表达式计算(注意数进栈与计算的先后顺序)
#include<iostream>
#include<string>
#include<unordered_map>
#include<stack>
using namespace std;
stack<int> num;
stack<char> opt;
unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
void cul() {
int x = num.top();
num.pop();
int y = num.top();
num.pop();
char symbol = opt.top();
opt.pop();
int z = 0;
if (symbol == '+') z = y + x;
if (symbol == '-') z = y - x;
if (symbol == '*') z = y * x;
if (symbol == '/') z = y / x;
num.push(z);
}
int main() {
string s;
cin >> s;
for (int i = 0; i < s.size(); i ++ ) {
//先处理num
if (isdigit(s[i])) {
int j = i, x = 0;
while(j < s.size() && isdigit(s[j])) {
x = x * 10 + s[j] - '0';
j ++ ;
}
num.push(x);
i = j - 1;
}
else if (s[i] == '(') {
opt.push(s[i]);
}
else if (s[i] == ')') {
while(opt.top() != '(') cul();
opt.pop();
}
//处理符号
else {
while(opt.size() && h[opt.top()] >= h[s[i]]) {
cul();
}
opt.push(s[i]);
}
}
while(opt.size()) cul();
cout << num.top() << endl;
}