leetcode每日一题(2020-06-30):剑指 Offer 09. 用两个栈实现队列

题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

今日学习:
1.没学啥好像。。。

题解:

var CQueue = function() {
    // this.queue = []
    this.stack1 = []
    this.stack2 = []
};

/** 
 * @param {number} value
 * @return {void}
 */
CQueue.prototype.appendTail = function(value) {
    // this.queue.push(value)
    this.stack1.push(value)
};

/**
 * @return {number}
 */
CQueue.prototype.deleteHead = function() {
    // if(this.queue.length != 0) {
    //     return this.queue.shift()
    // }else {
    //     return -1
    // }

    // if(this.stack2.length == 0) {
    //     while(this.stack1.length) {
    //         this.stack2.push(this.stack1.pop());
    //     }
    // }
    // return this.stack2.pop() || -1;

    //如果第二个栈中有元素,直接pop()
    if(this.stack2.length){
        return this.stack2.pop()
    }
    //如果第一个栈为空,则直接返回--1
    if(!this.stack1.length) return -1
    //将第一个栈中的元素倒置进第二个栈中
    while(this.stack1.length){
        this.stack2.push(this.stack1.pop())
    }
    return this.stack2.pop()
};

/**
 * Your CQueue object will be instantiated and called as such:
 * var obj = new CQueue()
 * obj.appendTail(value)
 * var param_2 = obj.deleteHead()
 */
posted @ 2020-06-30 09:21  秋夜星空  阅读(70)  评论(0编辑  收藏  举报