博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Two stacks implements queue.

Posted on 2013-07-25 13:41  钟悍  阅读(152)  评论(0编辑  收藏  举报
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();
    }
}