Share my c++ code using two stack


  • 1
    L
    class MinStack {
    private:
        stack<int> min_stack;
        stack<int> min_ele;
        int minele = 0;
    public:
        void push(int x) {
            min_stack.push(x);
            if(min_stack.size() == 1) {
                min_ele.push(x);
                minele = x;
            }else if(x <= minele){
                    minele = x;
                    min_ele.push(x);
            }
        }
    
        void pop() {
            if(min_stack.top() == minele){
                min_stack.pop();
                min_ele.pop();
                if(!min_ele.empty())
                minele = min_ele.top();
            }else min_stack.pop();
        }
    
        int top() {
            return min_stack.top();
        }
    
        int getMin() {
            return minele;
        }
    };

Log in to reply
 

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