[C++ brushing notes] stack classic OJ (minimum stack, stack push pop sequence, reverse Polish expression evaluation)

 Record the classic OJ and wrong questions in the learning process

(1) 155. Minimal Stack - LeetCode

class MinStack {
public:
    MinStack() {

    }
    
    void push(int val) {
        // 只要是压栈,先将元素保存到_st中
        _st.push(val);
        
        // 如果x小于_minst中栈顶的元素,将x再压入_minst中
        if(_minst.empty() || val <= _minst.top())
            _minst.push(val);
    }
    
    void pop() {
        // 如果_minst栈顶的元素等于出栈的元素,_min顶的元素要移除
        if(_st.top() == _minst.top())
            _minst.pop();

        _st.pop();
    }
    
    int top() {
        return _st.top();
    }
    
    int getMin() {
        return _minst.top();
    }
    
    // 保存栈中的元素
    stack<int> _st;

    // 保存栈的最小值
    stack<int> _minst;
};

(2) Push-in and pop-up sequences of the stack

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
    stack<int> st;
    size_t popi = 0;

    for(auto e : pushV)
    {
        //入栈
        st.push(e);

        //跟出栈序列相比,相同就出
        while(!st.empty() && st.top() == popV[popi])
        {
            st.pop();
            popi++;
        }
    }

    //栈为非空则报错
    return st.empty();

    }
};

(3) 150. Reverse Polish Expression Evaluation - LeetCode

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;

        for(auto str : tokens)
        {
            //遇到运算符就运算,没有遇到就压栈
            if(str=="+" || str=="-" || str=="*" || str=="/")
            {
                int right = st.top();
                st.pop();
                int left = st.top();
                st.pop();

                switch(str[0])//这里不可以使用str
                {
                    case '+':
                        st.push(left+right);
                        break;
                    case '-':
                        st.push(left-right);
                        break;
                    case '*':
                        st.push(left*right);
                        break;
                    case '/':
                        st.push(left/right);
                        break;
                }
            }
            else
            {
                //stoi可以将字符转化成整形
                st.push(stoi(str));
            }
        }

        return st.top();
    }
};

The above is all the content of this note. If it is helpful to you, you may wish to like, bookmark, and follow. Thank you for reading.

Guess you like

Origin blog.csdn.net/Captain_ldx/article/details/129670839