两个栈实现队列

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:队列先进先出,栈后进后出,那么入队操作就可以使简单的push到一个栈中,而pop操作就需要把一个栈里所有元素弹到另一个栈里,然后pop栈顶

 Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack2.push(node);
    }
    public int pop() {
        //出队栈不为空!!!
        if(stack1.empty()){
            while(!stack2.empty()){
                stack1.push(stack2.pop());
            }
        }
        return stack1.pop();
    }
原文地址:https://www.cnblogs.com/team42/p/6681171.html