zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

用两个栈实现队列_05

2023-04-18 16:10:06 时间

思路

stack1永远做栈压入,永远先从栈2拿数据,栈2空了再从栈1拿,保证顺序性

public class StockToQueue {

    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

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

    /**
     * 永远从非空的栈2先拿数据
     */
    public int pop() {
        if (stack1.empty()&&stack2.empty()){
            throw new RuntimeException("queue is empty");
        }

        if (stack2.empty()){
            while (!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}