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
一个栈的案例:
int evalRPN(vector<string>& tokens) {
if (tokens.size() == 0)return 0;
stack<int> res;
int sum = 0;
for (int i = 0; i < tokens.size(); i++){
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")res.push(stoi(tokens[i]));
else{
int temp2 = res.top(); res.pop();
int temp1 = res.top(); res.pop();
if (tokens[i] == "+") res.push(temp1 + temp2);
else if (tokens[i] == "-") res.push(temp1 - temp2);
else if (tokens[i] == "*") res.push(temp1 * temp2);
else if (tokens[i] == "/") res.push(temp1 / temp2);
}
}
return res.top();
}