天天看點

【棧的應用】字首表達式求值

#include<iostream>
#include<stack>
#include<math.h>
#include<string>
using namespace std;
stack<int> num;
stack<char> ops;
string s;
void cal(char c)
{
    int a=num.top();
    num.pop();
    int b=num.top();
    num.pop();
    int d;
    if(c=='+') d=a+b;
    else if(c=='-') d=a-b;
    else if(c=='*') d=a*b;
    else if(c=='/') d=a/b;
    else d=pow(a,b);
    num.push(d);
}
int main(){
    cin>>s;
    for(int i=s.size()-1;i>=0;i--){
        if(s[i]>='0'&&s[i]<='9'){
            num.push(s[i]-'0');
        }
        else {
            cal(s[i]);
        }
    }
    cout<<num.top()<<endl;
    return 0;
}
           

繼續閱讀