mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 01:20:05 +08:00
1.2 KiB
1.2 KiB
题目地址
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
思路
这道题目相当于是二叉树中的后序遍历,也引申出栈与递归之间在某种程度上是可以转换的!
C++代码
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(num2 + num1);
if (tokens[i] == "-") st.push(num2 - num1);
if (tokens[i] == "*") st.push(num2 * num1);
if (tokens[i] == "/") st.push(num2 / num1);
} else {
st.push(stoi(tokens[i]));
}
}
return st.top();
}
};
更过算法干货文章持续更新,可以微信搜索「代码随想录」第一时间围观,关注后,回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等,就可以获得我多年整理的学习资料。