Min Stack

    /*
    * @param a: An integer
    */
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<Integer>();
        minStack = new Stack<Integer>();
    }

    /*
     * @param number: An integer
     * @return: nothing
     */
    public void push(int number) {

        stack.push(number);

        if (minStack.isEmpty()) {
            minStack.push(number);
        } else {
            minStack.push(Math.min(minStack.peek(), number));
        }
    }

    public int pop() {

        minStack.pop();
        return stack.pop();
    }

    public int min() {

        return minStack.peek();
    }
}

A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference:

Deque<Integer> stack = new ArrayDeque<Integer>();

boolean offerFirst(E e)

boolean offerLast(E e)

E peekFirst()

E peekLast()

E pollFirst()

E pollLast()

int size()

boolean contains(Object o)

isEmpty() // inherit from java.util.Collection

Stack class:

1) don't have its own interface;

2) is a subclass of Vector class - which is based on resizable array; and no linked list implementation of stack

In Deque interface we don't have such problems including two implementations: resizable array - ArrayDeque, linked list - LinkedList

// Using Deque
public class MinStack {
    private Deque<Integer> stack;
    private Deque<Integer> minStack;

    public MinStack() {
        stack = new ArrayDeque<Integer>();
        minStack = new ArrayDeque<Integer>();
    }

    /*
     * @param number: An integer
     * @return: nothing
     */
    public void push(int number) {
        stack.offerFirst(number);

        if(minStack.isEmpty()) {
            minStack.offerFirst(number);
        } else {
            minStack.offerFirst(Math.min(number, minStack.peekFirst()));
        }
    }

    public int pop() {
        minStack.pollFirst();
        return stack.pollFirst();
    }

    public int min() {
        return minStack.peekFirst();
    }
}

results matching ""

    No results matching ""