Loading...

用两个栈实现队列

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        if(stack2.isEmpty()){
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        } 
        return stack2.pop();
    }

小贴士

  • 所有入队的元素,无条件直接压入 stack1
  • stack1 只管入队,stack2 只管出队,并且只有当stack2 为空时才进行一次性倒栈
Code Road Record