28ms C++ solution. Single linked-list without using any other libraries


  • 1
    B
    class MinStack {
        
        struct Node {
            int val;
            int min;
            Node *next;
        };
        
    private:
    
        Node *head;
        
        
    public:
    
        MinStack(){
            head = NULL;
        }
        
        ~MinStack() {
            delete head;
        }
        
        void push(int x) {
            Node* temp = new Node;
            Node** headaddr = &head;
            temp->val = x;
            if (head){
                if (head->min > x){
                    temp->min = x;
                } else {
                    temp->min = head->min;
                }
            }else {
                temp->min = x;
            }
            temp->next = head;
            *headaddr = temp;
        }
    
        void pop() {
            Node *temp = head;
            head = head->next;
            delete temp;
        }
    
        int top() {
            return head->val;
        }
    
        int getMin() {
            return head->min;
        }
    };

  • 0
    G

    The worst code ever...


Log in to reply
 

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