Run Time Error. Help~


  • 1
    X

    My code:

    class MinStack {
    public:
        void push(int x) {
            istack.push(x);
            if(x<=minstack.top()||minstack.empty()){
                minstack.push(x);
            }
        }
    
        void pop() {
            if(istack.top()==minstack.top()){
                minstack.pop();
            }
            istack.pop();
        }
    
        int top() {
            return istack.top();
        }
    
        int getMin() {
            return minstack.top();
        }
    private:
        stack<int> istack;
        stack<int> minstack;
    };
    

    Run time error:
    Last executed input: push(-3),getMin

    I don't know why it is wrong...
    Help~
    Thank you!


  • 1
    R

    void push(int x) {
    istack.push(x);
    if(x<=minstack.top()||minstack.empty()){
    minstack.push(x);
    }
    }

    you should switch the order of the conditions
    there might be a problem when you call the top on an empty stack

    || is a short circuit operator, so pay attention to the order of conditions

    minstack.empty() || x<=minstack.top()


  • 0
    X

    Thank you very much!
    It is workable after I changed the order of conditions.


Log in to reply
 

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