clear C++ Linked-list solution, every node has val and min


  • 0

    head->min records the current minimal value of all the numbers inside the stack

    class MinStack {
    private:
        struct ListNode {
            int val, min;
            ListNode* next;
        };
        ListNode *head;
    public:
        /** initialize your data structure here. */
        MinStack() {
            head = NULL;
        }
        
        void push(int x) {
            ListNode* tmp = new ListNode();
            tmp->val = tmp->min = x;
            if (head == NULL) head = tmp;
                else {
                    tmp->min = min(head->min, tmp->min);
                    tmp->next = head;
                    head = tmp;
                }
        }
        
        void pop() {
            head = head->next;
        }
        
        int top() {
            return head->val;
        }
        
        int getMin() {
            return head->min;
        }
    };
    

Log in to reply
 

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