两个栈实现队列

解决思路:

两个栈stack1和stack2 。
开始时,每次添加队尾元素到stack1中。
如果需要弹出队头元素,则将stack1中的元素弹出并push到stack2中,再将stack2的栈顶元素弹出,即为弹出了队头元素。
如果stack2中是非空的,再在队尾中添加元素的时候仍然加到stack1中,从stack2中弹出队头元素。
只有当stack2为空的时候,弹出队头元素才需要将stack1中的元素转移到stack2中。

public class MyQueue {

    private Stack<Integer> pushQueue = new Stack<>();
    private Stack<Integer> popQueue = new Stack<>();

    public MyQueue() {
    }

    public void push(int num) {
        pushQueue.push(num);
    }

    public int pop() {
        if (pushQueue.isEmpty() && popQueue.isEmpty()) {
            throw new RuntimeException("queue is empty!");
        }
        if (popQueue.isEmpty()) {
            while (!pushQueue.isEmpty()) {
                popQueue.push(pushQueue.pop());
            }
        }
        return popQueue.pop();
    }
}
原文地址:https://www.cnblogs.com/cherish010/p/14000680.html