题目链接:
设置一个栈,存放操作数
从左到右依次读入后缀表达式的每一个操作数/运算符/结束符:
①若读到的是操作数,将它压入堆栈。
②若读到的是运算符,就从操作数栈中连续弹出两个元素(操
作数),进行相应的运算,并将结果压入栈中。
③读入结束符时,栈顶元素就是计算结果。
class Solution {
public:
stack<int> s;
bool isnum(string s) {
if (s == "+" || s == "-" || s == "*" || s == "/") return false;
return true;
}
int evalRPN(vector<string>& tokens) {
for (auto x : tokens) {
if (isnum(x)) {
s.push(stoi(x));
}
else {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
int c;
if (x == "+") c = a + b;
if (x == "-") c = a - b;
if (x == "*") c = a * b;
if (x == "/") c = a / b;
s.push(c);
}
}
return s.top();
}
};
注:
后缀表达式也称为逆波兰表达式。