思路:
用一个栈即可. 很简单. 因为保证没有错误输入, 所以还不用考虑特殊情况了. 每次pop两次top, 操作, 再push进去.
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (string str : tokens) {
if (str == "+") {
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
stk.push(num1 + num2);
}
else if (str == "-") {
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
stk.push(num1 - num2);
}
else if (str == "*") {
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
stk.push(num1 * num2);
}
else if (str == "/") {
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
stk.push(num1 / num2);
}
else
stk.push(stoi(str));
}
return stk.top();
}