# 剑指Offer09-用两个栈实现队列-简单

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/ (opens new window)

image-20220110165501769

# 我的解答

一个入队栈只用来往里塞值,一个出队栈用来接收入队栈中pop出来的值,

最终用出队栈出栈实现队列的删除队列头操作

var CQueue = function() {
    // 入队栈
    this.pushStack = [];
    // 出队栈
    this.popStack = [];
};

/** 
 * @param {number} value
 * @return {void}
 */

// 所有入队操作都在 pushStack栈中完成
CQueue.prototype.appendTail = function(value) {
    this.pushStack.push(value);
};

/**
 * @return {number}
 */
CQueue.prototype.deleteHead = function() {
    // 队列中没有元素 -1
    if(!this.pushStack.length && !this.popStack.length) {
        return -1;
    }
    // 出队栈中无值,从入队栈中取
    if(!this.popStack.length) {
        while(this.pushStack.length) {
            this.popStack.push(this.pushStack.pop())
        }
    }
     
    // 出队栈中有值 直接出栈
    return this.popStack.pop()

};

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

# 官方解答

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/solution/mian-shi-ti-09-yong-liang-ge-zhan-shi-xian-dui-l-3/ (opens new window)

# 优质解答

上次更新: 11/8/2024, 10:19:43 AM