
下面给出图解:

下面给出代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
//循环遍历表达式 范围for
for(const auto& str : tokens) {
if(str == "+" || str == "-"
|| str == "*" || str == "/") {
//遇到操作符
//取出两个操作数
int right = st.top();
st.pop();
int left = st.top();
st.pop();
//计算结果并入栈
if(str == "+")
st.push(left + right);
else if(str == "-")
st.push(left - right);
else if(str == "*")
st.push(left * right);
else
st.push(left / right);
}
else {
//遇到操作数
//入栈, 注意要转换成整型, 使用string的库函数即可
st.push(stoi(str));
}
}
//栈顶即为最后的结果
return st.top();
}
};
版权声明:本文为weixin_45818891原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。