逆波兰表达式求值(栈)

题目:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        //根据逆波兰表示法,求表达式的值。
        stack<int> st;
        int n = tokens.size();
        for(int i = 0,x,y;i < n;i++) {
            string str = tokens[i];
            if(str == "+") {
                x = st.top();st.pop();
                y = st.top();st.pop();
                st.push(y+x);
            }
            else if(str == "-") {
                x = st.top();st.pop();
                y = st.top();st.pop();
                st.push(y-x);
            }
            else if(str == "*") {
                x = st.top();st.pop();
                y = st.top();st.pop();
                st.push(y*x);
            }
            else if(str == "/") {
                x = st.top();st.pop();
                y = st.top();st.pop();
                st.push(y/x);
            }
            else {
                x = stoi(str);
                st.push(x);
            }
        }
        return st.top();
    }
};
发布了152 篇原创文章 · 获赞 2 · 访问量 6457

猜你喜欢

转载自blog.csdn.net/weixin_43918473/article/details/104644542