[LeetCode]Min Stack

implement Stack, getMin() is always O(1)

class MinStack {
    LinkedList<Integer> main = new LinkedList<Integer>();
    LinkedList<Integer> min = new LinkedList<Integer>();
    public void push(int x) {
        main.push(x);
        if(min.size() == 0) {
            min.push(x);
        }else{
            if (min.peek() >= x ) {
                min.push(x);
            }
        }
    }

    public void pop() {
        if(main.size() != 0) {
            if(main.peek().equals(min.peek())) {
                min.pop();
            }
            main.pop();
        }
    }

    public int top() {
        if(main.size() != 0) {
            return main.peek();
        }else {
            return 0;
        }
    }

    public int getMin() {
        if(min.size() != 0) {
            return min.peek();
        } else {
            return 0;
        }
    }
}
posted on 2015-03-31 01:18  Seth_L  阅读(103)  评论(0编辑  收藏  举报