LeetCode | 155. Min Stack

Description

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

Solution

Code

class MinStack {
    public MinStack() {
    }
    private Node first = null;
    private int size = 0;
    private class Node{
        int item;
        int minInt;
        Node next;
    }
    public void push(int x) {
        Node oldFirst = first;
        first = new Node();
        first.item = x;
        first.next = oldFirst;   
        if(oldFirst == null){
            first.minInt = x;
        }else{
            first.minInt = x < oldFirst.minInt? x: oldFirst.minInt;
        }
        size++;
    }
    public void pop() {
        first = first.next;
        size--;
    }
    public int top() {
        return first.item;
    }
    public int getMin() {
        return first.minInt; 
    }
}
Comments
Write a Comment