Implement Stack using Queues

https://leetcode.com/problems/implement-stack-using-queues/description/

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.

  • pop() -- Removes the element on top of the stack.

  • top() -- Get the top element.

  • empty() -- Return whether the stack is empty.

Thoughts

和stack不同,多用一次queue并不能把元素顺序倒过来。无论用几个queue,依然是顺序的。因此只能新进入一个元素时,手动把所有元素拿出来把新元素放进去,再把之前所有元素塞回去。

Code

class MyStack {
    Queue<Integer> queue1, queue2;
    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    /** Push element x onto stack. */
    public void push(int x) {
        while (!queue1.isEmpty()) {
            queue2.offer(queue1.poll());
        }
        queue1.offer(x);
        while (!queue2.isEmpty()) {
            queue1.offer(queue2.poll());
        }
    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue1.poll();
    }

    /** Get the top element. */
    public int top() {
        return queue1.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

Analysis

push的时间复杂度为O(N), 其余O(1).

Ver.2

其实用一个queue就行。把新元素先塞进去,然后把原来的元素依次扔到queue尾。

// Push element x onto stack.
    public void push(int x) 
    {
       queue.add(x);
       for(int i=0;i<queue.size()-1;i++)
       {
           queue.add(queue.poll());
       }
    }

Last updated