两个栈实现一个队列

分析

使用两个栈:in、out
in用于元素进入(入队),out用于取出元素(出队)
push时,只管加入in栈即可
pop时,把in栈中的移到out,此时out栈是FIFO,出队直接弹出栈顶即可。 (需要注意的是,out为空时才从in搬过去,否则直接取即可)

实现:

    Stack<Integer> in = new Stack<Integer>();
    Stack<Integer> out = new Stack<Integer>();

    public void push(int node) {
        in.push(node);
    }

    public int pop() throws Exception {
        if (out.isEmpty())
            while (!in.isEmpty())
                out.push(in.pop());
        if (out.isEmpty())
            throw new Exception("队为空!");
        return out.pop();
    }
posted @ 2020-04-27 18:37  Edwin_Xu  阅读(188)  评论(0)    收藏  举报