栈与队列 - 用栈实现队列

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()
 */
相关推荐
ZC跨境爬虫13 分钟前
跟着 MDN 学 HTML day_41:(DOMParser 接口详解)
前端·javascript·ui·html·音视频
threelab20 分钟前
Three.js 概率统计可视化 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能
光影少年26 分钟前
useLayoutEffect 和 useEffect 区别、使用场景
开发语言·前端·javascript
下雨打伞干嘛43 分钟前
redux的使用
开发语言·javascript·ecmascript
small_white_robot1 小时前
idek-2022 web 全wp——持续更新
开发语言·前端·javascript·网络·安全·web安全·网络安全
sp421 小时前
NativeScript 5.1:直接集成 Objective-C 代码
前端·javascript
px不是xp1 小时前
【灶台导航】 RAG系统的容错设计:从向量搜索到关键词降级,一个都不能少
javascript·微信小程序·notepad++·rag
Sanri.1 小时前
JavaScript基础语法6
开发语言·javascript·ecmascript
hhb_6181 小时前
JavaScript核心技术要点梳理与实战应用案例解析
开发语言·javascript·ecmascript
廖松洋(Alina)2 小时前
03主入口页面与导航结构-鸿蒙PC端Electron开发
前端·javascript·华为·electron·开源·harmonyos·鸿蒙