Have no idea about the Memory Limit Exceeded problem. Can somebody help me to get out??


  • 0
    O
    struct Node {
    int val;
    Node *next;
    
    Node (int x, Node *n = NULL): val (x), next (n) {};
    

    };

    class MinStack {

    private :
    Node *head;
    int min;

    public :
    MinStack () {head = NULL;}

    ~MinStack () {
        Node *p = head;
        Node *q;
        while (p != NULL) {
            q = p;
            p = p -> next;
            delete q;
        }
        head = NULL;
    }
    
    void push (int x) {
        Node *p = new Node (x, head);
        if (head == NULL || x < min)
            min = x;
            
        head = p;
    }
    
    void pop () {
        Node *p = head;
        head = head -> next;
        delete p;
    }
    
    int top () {
        return head -> val;
    }
    
    int getMin () {
        return min;
    }
    

    };


  • 0
    D

    It seems that you didn't have your member variable "min" initialized in the constructor...


  • 0
    O

    Yeah, but actually it is no problem as it can be set a value when "push" is called.
    And I don't think this has some problem with the MLE.

    Actually I found that this algorithm is wrong. I should not use min as an int but should use it as a stack. Because when pop is called maybe the minimum element is been poped. That is my fault anyway.


Log in to reply
 

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