What's the problem with this code?!


  • 0
    S
    struct StackNode{
        int val;
        StackNode *next;
        StackNode(int x) : val(x), next(NULL) {}
    };
    
    class MinStack {
    private:
        StackNode* Top;
        StackNode* Min;
    public:
        void push(int x) {
            if(Top == NULL){
                Top = new StackNode(x);
                x;
            }
            else
            {
                StackNode *NewTop = new StackNode(x);
                NewTop->next = Top;
                Top = NewTop;
                if(x < Min->val)
                    Min = Top;
            }
        }
    
        void pop() {
           if (Top != NULL){
        		if (Top == Min)
        			Min = Top->next;
        		Top = Top->next;
        		StackNode *minTmp = Top;
        		while (minTmp != NULL){
        			if (minTmp->val < Min->val)
        				Min = minTmp;
        			minTmp = minTmp->next;
        		}
    	    }
        }
    
        int top() {
            return Top->val;
        }
    
        int getMin() {
            return Min->val;
        }
    };
    

    Thanks!


  • 0
    D

    where is your def of Min?
    your private min seems useless


  • 0
    S

    sorry, I changed that before posting the code. Please review the updated code


  • 0
    F

    you should inilialize your pointer Min correctly, or you will get an illegal access to Min at the first push.


Log in to reply
 

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