算法题:7、用栈实现队列

题目描述

用栈来实现队列,完成队列的Push和Pop操作。

解题思路

队列是先进先出,栈是先进后出,我们需要两个栈,in栈用来处理入栈(push)操作,out栈用来处理出栈(pop)操作。一个元素进入in栈以后,出栈的顺序被反转。当元素要出栈时,
需要先进入out栈,此时元素出栈的顺序再一次被反转,因此出栈顺序和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。

代码

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

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

public int pop() throws Exception {
    if (out.empty()) {
        while (!in.empty()) {
            out.push(in.pop());
        }
    }

    if (out.empty()) {
        throw new Exception("queue is empty");
    }

    return out.pop();
}
原文地址:https://www.cnblogs.com/fcb-it/p/12833737.html