标签:栈
NO.150 逆波兰表达式求值
class Solution {
public:
int str2num(string s)
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
int evalRPN(vector<string>& tokens) {
stack <int> s;
int n = tokens.size();
int ans;
if(tokens[0] != "+" && tokens[0] != "-" && tokens[0] != "*" && tokens[0] != "/")
ans = str2num(tokens[0]);
for(int i = 0; i <= n - 1 ; ++i)
{
if(tokens[i] == "+")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
ans = left + right;
s.push(ans);
}
else if(tokens[i] == "-")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
ans = left - right;
s.push(ans);
}
else if(tokens[i] == "*")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
ans = left * right;
s.push(ans);
}
else if(tokens[i] == "/")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
ans = left / right;
s.push(ans);
}
else
{
int r = str2num(tokens[i]);
s.push(r);
}
}
return ans;
}
};