Leetcode 150. 逆波兰表达式求值
题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/77d42268fc524ac3ac5a372dccc9cc27.png)
思路
- 扫描后缀表达式,遇到数字就将其入栈
- 当扫描到运算符时,将栈顶的两个元素取出来进行运算,然后将结果存入栈中
代码
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
if(tokens[i] == "+") st.push(num1 + num2);
if(tokens[i] == "-") st.push(num2 - num1);
if(tokens[i] == "*") st.push(num1 * num2);
if(tokens[i] == "/") st.push(num2 / num1);
}
else
{
st.push(stoi(tokens[i]));
}
}
int result = st.top();
st.pop();
return result;
}
};