232. Implement Queue using Stacks

正规做法是用一个STACK记录信息,每次PUSH都先把Stack里的所有东西弄到另一个stack里,添加当前X,然后再都弄回去。。

POP和PEEK都一样。

如果记录HEAD的话 PEEK就不用麻烦了。

也有用两个STACK的,一个正着,一个倒着,大同小异……各有利弊吧。。

time: push O(1) peek O(1) pop O(n) empty O(1)
space O(n)

class MyQueue {
    Stack<Integer> stk = new Stack<Integer>();
    boolean set = false;
    int head = 0;
    // Push element x to the back of queue.
    public void push(int x) {
        stk.push(x);
        if (!set) head = x;
        set = true;
    }

    // Removes the element from in front of queue.
    public void pop() {
        Stack<Integer> temp = new Stack<>();
        while (!stk.isEmpty()) {
            temp.push(stk.pop());
        }
        int res = temp.pop();
        if (!temp.isEmpty()) {
            head = temp.peek();
        } else {
            set = false;
        }
        while (!temp.isEmpty()) {
            stk.push(temp.pop());
        }
    }

    // Get the front element.
    public int peek() {
        return head;
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stk.isEmpty();
    }
}
posted @ 2016-11-05 04:38  哇呀呀..生气啦~  阅读(58)  评论(0)    收藏  举报