栈与队列 - 用栈实现队列

232. 用栈实现队列


方法一:

javascript 复制代码
var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackIn.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    const size = this.stackOut.length;
    if (size) {
        return this.stackOut.pop();
    }
    while (this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    const x = this.pop();
    this.stackOut.push(x);
    return x;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return !this.stackIn.length && !this.stackOut.length
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */
相关推荐
渣哥12 分钟前
从构造器注入到 setter:Spring 循环依赖的常见场景解析
javascript·后端·面试
鹏多多34 分钟前
前端音频兼容解决:音频神器howler.js从基础到进阶完整使用指南
前端·javascript·音视频开发
前端架构师-老李1 小时前
12、electron专题(electron-builder)
前端·javascript·electron
艾小码2 小时前
这份超全JavaScript函数指南让你从小白变大神
前端·javascript
reembarkation2 小时前
vue 右键菜单的实现
前端·javascript·vue.js
gplitems1237 小时前
Consua WordPress Theme — Business Consulting Sites That Convert With Clarity
javascript
雾削木9 小时前
stm32解锁芯片
javascript·stm32·单片机·嵌入式硬件·gitee
2301_768350239 小时前
Vue第二期:组件及组件化和组件的生命周期
前端·javascript·vue.js
小周同学:10 小时前
Vue项目中将界面转换为PDF并导出的实现方案
javascript·vue.js·pdf
今天头发还在吗11 小时前
【React】TimePicker进阶:解决开始时间可大于结束时间的业务场景与禁止自动排版
javascript·react.js·ant design