剑指 Offer 09. 用两个栈实现队列

传送门

代码

class CQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    public CQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }
    
    public void appendTail(int value) {
        stack1.push(value);
    }
    
    public int deleteHead() {
        while(!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
        if(stack2.isEmpty()) return -1;
        int res = stack2.pop();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
        return res;
    }
}

思路

栈只有一个口能进出,而且是 后进先出

队列需要先进先出,所以我们把 \(stack1\) 当做主栈,\(stack2\) 当做辅助栈

每次都把元素添加到队头,相当于把元素添加到\(stack1\) 中,

如果要删除元素的话,就必须把\(stack1\) 中所有的元素都倒出来放到 \(stack2\) 中,然后把\(stack1\) 最底下的那个元素删除,即可

然后再把元素重新放入\(stack1\) 中恢复原样

posted @ 2021-01-01 19:24  lukelmouse  阅读(53)  评论(0编辑  收藏  举报