My java solution without built in API


  • 0
    Y
    class Node {
    
        public int item;
        public Node next;
        public int min;
    
        public Node(int item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
    
    private Node head;
    private int size = 0;
    
    public void push(int x) {
        if (size == 0) {
            head = new Node(x, null);
            head.min = x;
        } else {
            int min = head.min > x? x: head.min;
            Node newNode = new Node(x, head);
            head = newNode;
            head.min = min;
        }
        size++;
    }
    
    public void pop() {
        if (size == 0) {
            return;
        }
        head = head.next;
        size--;
    }
    
    public int top() {
        return head.item;
    }
    
    public int getMin() {
        return head.min;
    }

  • 0
    J

    Pop() is problematic. You might be popping your minimum value and it's not getting updated.


  • 0
    W

    I think head.next.min has the min "before" the head was insert, i.e. it would be correct min after the head is popped.


Log in to reply
 

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