leetcode----用两个栈实现队列(JavaScript解法)

    技术2022-07-10  106

    一、题目描述

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

    二、示例

    三、解题思路

    我们使用数组的pop()和push()方法来实现。具体的思路:栈一用作入栈操作,栈二用作出栈操作,栈二有三种情况

    四、代码

    var CQueue = function() { this.stack1 = [] this.stack2 = [] }; /** * @param {number} value * @return {void} */ CQueue.prototype.appendTail = function(value) { this.stack1.push(value) }; /** * @return {number} */ CQueue.prototype.deleteHead = function() { // 一. 2 不为空,直接取 if (this.stack2.length) return this.stack2.pop() // 二. 2 为空 循环1, 往2中继续添加元素 while(this.stack1.length){ this.stack2.push(this.stack1.pop()) } return this.stack2.pop() || -1 }; /** * Your CQueue object will be instantiated and called as such: * var obj = new CQueue() * obj.appendTail(value) * var param_2 = obj.deleteHead() */

    五、结果

    Processed: 0.010, SQL: 9