/*
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
#include<iostream>
#include<string>
#include<stack>
#include<vector>
using namespace std;
int cal(int num1,int num2,string ch)
{
int result;
if(ch=="+")
{
result=num1+num2;
}
else if(ch=="-")
{
result=num1-num2;
}
else if(ch=="*")
{
result=num1*num2;
}
else if(ch=="/")
{
result=num1/num2;
}
return result;
}
int RPN(vector<string> &tokens)
{
int i;
stack<int> opd;
for(i=0;i<tokens.size();i++)
{
if(tokens[i]=="+"||tokens[i]=="-" ||tokens[i]=="*"||tokens[i]=="/")
{
int num2=opd.top();
opd.pop();
int num1=opd.top();
opd.pop();
opd.push(cal(num1,num2,tokens[i]));
}
else
{
opd.push(atoi(tokens[i].c_str()));
}
}
return opd.top();
}
int main()
{
string str[]={"2", "1", "+", "3", "*"};
string str1[]={"4", "13", "5", "/", "+"};
vector<string> tokens(str,str+sizeof(str)/sizeof(str[0]));
vector<string> tokens1(str1,str1+sizeof(str1)/sizeof(str1[0]));
/*
for(vector<string>::iterator iter=tokens.begin();iter!=tokens.end();++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
*/
cout<<RPN(tokens)<<endl;
cout<<RPN(tokens1)<<endl;
system("pause");
return 0;
}