Implement Stack Using Queues

不容易写对

class MyStack {
    // Push element x onto stack.
    Queue<Integer> normalQueue = new LinkedList<Integer>();
    Queue<Integer> reverseQueue = new LinkedList<Integer>();
    public void push(int x) {
        if (!reverseQueue.isEmpty()) {
            normalQueue.offer(reverseQueue.poll());
        }
        normalQueue.offer(x);
    }

    // Removes the element on top of the stack.
    public void pop() {
        move();
        reverseQueue.poll();
    }

    // Get the top element.
    public int top() {
        move();
        return reverseQueue.peek();
    }

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

    private void move() {
        if (reverseQueue.isEmpty()) {
            while (normalQueue.size() > 1) {
                reverseQueue.offer(normalQueue.poll());
            }
            Queue<Integer> tmp = reverseQueue;
            reverseQueue = normalQueue;
            normalQueue = tmp;
        }
    }
}

Leave a comment