Files
leetcode-master/problems/0150.逆波兰表达式求值.md
youngyangyang04 329919b223 Update
2020-07-21 19:44:28 +08:00

1.2 KiB
Raw Blame History

题目地址

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」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。