Explained C++ Soln using Stack


#1

While traversing the vector A, we encounter two types of string.

  1. A[i] is an integer
  2. A[i] is a operation.

Case 1: Whenever we encounter integer, we push it into our stack
Case 2: We apply the operation to the last two elements added to our stack. Lets call the previous two elements as temp1 and temp2. We store the result inside temp1 and push it again to stack.

Successively doing this will result in stack containing finally only one element and that my friends would be the answer to the question!

   int Solution::evalRPN(vector<string> &A) {
    
    stack <int> stk;
    for(auto s : A){
        if(s.size()>1 || isdigit(s[0]))stk.push(stoi(s));
        else{
            auto temp2 = stk.top(); stk.pop();
            auto temp1 = stk.top(); stk.pop();
            switch(s[0]){
                case '+': temp1+=temp2; break;
                case '-': temp1-=temp2; break;
                case '*': temp1*=temp2; break;
                case '/': temp1/=temp2; break;
            }
            stk.push(temp1);
        }
    }
    return stk.top();
}