C++: Using double linked list for the stack


  • 0
    J

    Double linked list allows for O(1) element removal, which helps with popMax

    class MaxStack {
    private:
        list<int> st;    
        using Iter = list<int>::iterator;
        map<int, stack<Iter>> m;
        
    public:
        /** initialize your data structure here. */
        MaxStack() {        
        }
        
        void push(int x) {
            st.push_back(x);
            m[x].push(prev(st.end()));
        }
        
        int pop() {
            int x = st.back();
            st.pop_back();
            
            auto f = m.find(x);
            f->second.pop();
            if (f->second.empty())
                m.erase(f);
            
            return x;
        }
        
        int top() {
            int x = st.back();
            return x;
        }
        
        int peekMax() {
            return m.rbegin()->first;
        }
        
        int popMax() {
            auto top = prev(m.end());
            int x = top->first;        
            
            auto& stNode = top->second;
            list<int>::iterator del = stNode.top();
            stNode.pop();
            if (stNode.empty()) {
                m.erase(top);
            }
            
            st.erase(del);        
            return x;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.