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

吞佛童子2022年10月10日
  • algorithm
  • Queue
  • Stack
小于 1 分钟

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

难度: 🌕

问题描述

img_14.png


解法

class CQueue {
    // 思路:
    // 双栈,一个作为辅助栈
    LinkedList<Integer> stack;
    LinkedList<Integer> ts;

    public CQueue() {
        stack = new LinkedList<>();
        ts = new LinkedList<>();
    }
    
    public void appendTail(int value) {
        stack.push(value);
    }
    
    public int deleteHead() {
        // 将 stack 的全部元素压入 ts
        int res = -1;
        if(!ts.isEmpty()) {
            return ts.pop();
        }
        // ts.isEmpty()
        if(stack.isEmpty()) {
            return res;
        }
        // 将 stack 的元素全部压入 ts
        while(!stack.isEmpty()) {
            ts.push(stack.pop());
        }
        res = ts.pop();
        return res;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

输出

img_13.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou