栈的应用
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
stack<int> s1;
stack<char> s2;
int get_pri(char c){
if(c == '+' || c == '-') return 1;
if(c == '*' || c == '/') return 2;
else return 0;
}
int get_res(int a, int b, char op){
if(op == '-') return b - a;
if(op == '+') return a + b;
if(op == '*') return a * b;
if(op == '/') return b / a;
}
int main(){
string s;
cin >> s;
for(int i = 0; i < s.size(); i ++){
char c = s[i];
if(c >= '0' && c <= '9'){
int res = c - '0';
while(i + 1 < s.size() && s[i + 1] >= '0' && s[i + 1] <= '9'){
res = res * 10 + (s[i + 1] - '0');
i ++;
}
s1.push(res);
}
else{
if(c == '(') s2.push(c);
else if(c == ')'){
while(s2.top() != '('){
int a = s1.top();
s1.pop();
int b = s1.top();
s1.pop();
char op = s2.top();
s2.pop();
s1.push(get_res(a, b, op));
}
s2.pop();
}
else{
while(!s2.empty() && get_pri(c) <= get_pri(s2.top()) ){
int a = s1.top();
s1.pop();
int b = s1.top();
s1.pop();
char op = s2.top();
s2.pop();
s1.push(get_res(a, b, op));
}
s2.push(c);
}
}
}
while(!s2.empty()){
int a = s1.top();
s1.pop();
int b = s1.top();
s1.pop();
char op = s2.top();
s2.pop();
s1.push(get_res(a, b, op));
}
cout << s1.top() << endl;
return 0;
}
(bushi