栈与队列 - 用栈实现队列

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()
 */
相关推荐
工业甲酰苯胺4 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
谢尔登8 小时前
【React Native】ScrollView 和 FlatList 组件
javascript·react native·react.js
然我8 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
kk_stoper9 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源
晨枫阳9 小时前
前端VUE项目-day1
前端·javascript·vue.js
颜酱9 小时前
抽离ant-design后台的公共查询设置
前端·javascript·ant design
绅士玖9 小时前
JavaScript 设计模式之单例模式🚀
前端·javascript·设计模式
Dream耀9 小时前
useReducer:React界的"灭霸手套",一个dispatch搞定所有状态乱局
前端·javascript·react.js
余大侠在劈柴9 小时前
pdf.js 开发指南:在 Web 项目中集成 PDF 预览功能
前端·javascript·学习·pdf
拾光拾趣录10 小时前
JavaScript屏幕切换检测方案
前端·javascript