Two stacks implements queue.

1609 ワード

class QueneWithTwoStacks<E> {

    private Stack<E> stack1 = new Stack<E>();

    private Stack<E> stack2 = new Stack<E>();



    public synchronized void add(E e) {

        stack1.push(e);

    }



    public synchronized E poll() throws Exception {

        if (stack2.size() <= 0) {

            while (!stack1.isEmpty()) {

                stack2.push(stack1.pop());

            }

        }

        if (stack2.size() == 0) {

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

        }

        return stack2.pop();

    }

}