pranay_teja
11/15/2018 - 9:00 AM

PrefixExpression-Evaluation

#include<bits/stdc++.h>
using namespace std;

// #Stack
// (infix) a+b*c = +a*bc (poftfix)

void operate(stack<int> &st, string operation){
    int a=st.top(); // left operand
    st.pop();
    int b=st.top(); // right operand
    st.pop();
    int res;
    if(operation=="+"){
        res=a+b;
    }else if(operation=="-"){
        res=a-b;
    }else if(operation=="*"){
        res=a*b;
    }else if(operation=="/"){
        res=a/b;
    }
    st.push(res);
}

int EvaluatePostfix(vector<string> x){
    stack<int> st;
    for(int i=x.size()-1;i>=0;i--){ // moving from last
        if(x[i]=="+" || x[i]=="-" || x[i]=="*" || x[i]=="/"){
            operate(st,x[i]);
            // cout<<st.top()<<" ";
        }else{
            st.push(stoi(x[i]));
        }
    }
    return st.top();
}

int main(){
    int n;
    cin>>n;
    vector<string> x(n);
    for(int i=0;i<n;i++){
        cin>>x[i];
    }
    cout<<EvaluatePostfix(x)<<endl;
}