Help about "Min Stack" with "Memory Limit Exceeded ",what`s wrong with my code


  • 0
    T
    typedef struct MINSTACK{
            MINSTACK* prev;
            int content;
            int min;
    }MINSTACK;
    
    class MinStack {
            MINSTACK* pcurr;   /* point to top(last) node */
    public:
        MinStack(){
            pcurr = NULL;
        }
        ~ MinStack(){
            while(pcurr != NULL){
                MINSTACK* tmp = pcurr;
                pcurr = pcurr->prev;
                delete tmp;
            }
        }
    
        void push(int x) {
            MINSTACK* tmp = pcurr;    /* store the old node */
            pcurr = new MINSTACK;    /* new a node && set the pcurr point to it */
            pcurr->prev = tmp;     /* make the new node`s prev pointer point to previous node,if it is the first node  pcurr->prev = NULL  */
            pcurr->content = x;
            if(pcurr->prev == NULL || x <= pcurr->prev->min){     /* set the node`s min=x,if it is the first node or x<=previous node`s min value */
                    pcurr->min = x;
            }
            else{  /*set the node`s min = previous node`s  min value,if previous node isn`t NULL && x>previous node`s min value */                                                  
                    pcurr->min = pcurr->prev->min;
            }
        }
        void pop() {
           if(pcurr == NULL){
                return;
            }
            MINSTACK* tmp = pcurr;
            pcurr = pcurr->prev;     
            delete tmp;
        }
    
        int top() {
            return pcurr->content;
        }
    
        int getMin() {
            return pcurr->min;
        }
    };

  • 0
    M

    can you put in some comments within your code so that its easier to understand and find out the error?


  • 0
    T

    thanks for your suggestion,I have given some comments on my code,please see again!


Log in to reply
 

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