C++ Stack+Recursion


#1

int to_int(string s)
{
stringstream geek(s);
int x = 0;
geek >> x;
return x;
}
int sol(stack &s)
{
if(s.empty()) return 1;
int ans,operand1,operand2;

string a = s.top();
s.pop();

if(s.top() =="+" || s.top() =="/" || s.top() =="*" || s.top()=="-") operand1=sol(s);
else 
{
    operand1 = to_int(s.top());
    s.pop();
}

if(s.top() =="+" || s.top() =="/" || s.top() =="*" || s.top()=="-") operand2=sol(s);
else
{
    operand2 = to_int(s.top());
    s.pop();
}
    
if(a=="/")
    ans = operand2/operand1;
else if(a=="*")
    ans = operand2*operand1;
else if(a=="+")
    ans = operand2+operand1;
else
    ans = operand2-operand1;

return ans;

}

int Solution::evalRPN(vector &A) {
if(A.size()==1 || A.size()==0) return to_int(A[0]);
stack s;

for(auto i=A.begin();i!=A.end();i++)
{
    s.push(*i);
}
int ans = sol(s);
return ans;

}