Two queues implement stack.

class StackWithTwoQueue<E> {

    private Queue<E> queue1 = new LinkedList<E>();

    private Queue<E> queue2 = new LinkedList<E>();



    public synchronized void push(E e) {

        if (queue1.isEmpty()) {

            queue2.add(e);

        } else {

            queue1.add(e);

        }

    }



    public synchronized E pop() throws Exception {

        if (queue1.isEmpty() && queue2.isEmpty()) {

            throw new Exception("Stack is empty!");

        }

        if (!queue1.isEmpty()) {

            while (queue1.size() > 1) {

                queue2.add(queue1.poll());

            }

            return queue1.poll();

        } else {

            while (queue2.size() > 1) {

                queue1.add(queue2.poll());

            }

            return queue2.poll();

        }



    }

}

 

你可能感兴趣的:(Queue)