这道题主要思想是建立树与优先级的关系
#include<iostream>
#include<stack>
#include<unordered_map>
using namespace std;
stack<int> digit;
stack<char> op;
unordered_map<char,int> pr{{'+',1},{'-',1},{'*',2},{'/',2}};
void eval(){
int b = digit.top();digit.pop();
int a = digit.top();digit.pop();
char c = op.top();op.pop();
if(c == '+')
digit.push(a+b);
else if(c=='-')
digit.push(a-b);
else if(c=='*')
digit.push(a*b);
else
digit.push(a/b);
}
int main(){
string s;
cin >> s;
int len = s.length();
for( int i = 0 ; i < len ; i++ )
{
if( isdigit(s[i]) )
{
int j = i ;
int num = 0;
while( j < len && isdigit(s[j]) )
{
num = num * 10 + s[j] - '0';
j++;
}
digit.push(num);
i = j - 1 ;
}
else if (s[i] == '(' )
op.push(s[i]);
else if (s[i] == ')' )
{
while(op.size() && op.top()!='(') eval();
op.pop();
}
else
{
while( op.size() && pr[op.top()] >= pr[s[i]] ) eval();
op.push(s[i]);
}
}
while(op.size()) eval();
cout << digit.top();
}