225. Implement Stack using Queues

用Queue模拟Stack,用一个变量记录头就行了。

Time: pop O(n) 其余 O(1)
Space: O(n)

讨论区有人给出了O(1)的办法。。牛逼。 我就不考虑了。

class MyStack {
    Queue<Integer> q = new LinkedList<Integer>();
    int head = 0;
    // Push element x onto stack.
    public void push(int x) {
        q.add(x);
        head = x;
    }

    // Removes the element on top of the stack.
    public void pop() {
        Queue<Integer> temp = new LinkedList<>();
        while (q.size() != 1) {
            temp.add(q.poll());
        }
        q.poll();
        while (!temp.isEmpty()) {
            q.add(temp.peek());
            head = temp.poll();
        }
    }

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

    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }
}

posted @ 2016-11-06 06:34  哇呀呀..生气啦~  阅读(78)  评论(0)    收藏  举报