力扣:225 用队列实现栈

栈、队列

栈: 弹夹,后进先出

队列: 排队,先进先出

描述:

js 复制代码
	
var MyStack = function () {
    // 定义两个数组,模拟队列
    this.queue = []
    this._queue = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
    // 后插
    this.queue.push(x)
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
    // 返回栈顶元素,后进先出
    let ans
     while(this.queue.length > 1) {
        this._queue.push(this.queue.shift())
    }
    ans = this.queue.shift()
    while(this._queue.length){
        this.queue.push(this._queue.shift())
    }
    return ans
};

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
    // 返回栈顶元素,
    return this.queue.slice(-1)[0]
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
    return !this.queue.length
};

用数组模拟栈、队列,没啥意思

相关推荐
阿巴斯甜2 分钟前
AppFunctions 完整介绍
android
蜡台25 分钟前
Jetpack Compose 从入门到精通
android·前端·kotlin·compose·jepack
toooooop843 分钟前
踩坑:PHP7.2导出Excel正常,升级7.3文件损坏需修复
android·excel
学习星球1 小时前
Astro 全栈实战:拆解 RealWorld 项目
前端·javascript·架构·系统架构·前端框架·c5全栈
mmsx1 小时前
我明明调用了 zoomToBounds,地图却总是停在别处?延迟加到 5 秒也没用,真相只有一个
android·人工智能·bug·地图
圣保罗的大教堂1 小时前
leetcode 1386. 安排电影院座位 中等
leetcode
张元清2 小时前
React useTimeout Hook:声明式 setTimeout 与自动清理 (2026)
javascript·react.js
Nil2082 小时前
leetcode 146LRU缓存
算法·leetcode·缓存
禁止摆烂_才浅3 小时前
JavaScript 类型判断:instanceof 与 constructor 原理深度解析
前端·javascript·面试
蜡台3 小时前
Jetpack Compose 核心:状态管理 + Lazy 列表
android·kotlin·state·jetpack compose