力扣: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
};

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

相关推荐
Super 含17 分钟前
Android 包体积优化(一):APK 到底大在哪里?从 APK 结构到体积分析
android·ide·vscode
Nil20836 分钟前
leetcode 48旋转图像
算法·leetcode·职场和发展
Super 含1 小时前
Android 包体积优化(四):深入 ReDex——StripDebugInfo、InterDex 与 DEX 重排
android
嘟嘟07171 小时前
顺时针螺旋填充 n×n 矩阵:手撕 generateMatrix 的四个 for 循环
javascript·算法·面试
Nil2081 小时前
leetcode 206反转链表
算法·leetcode·链表
weixin_BYSJ19871 小时前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
安卓与AI研习社1 小时前
主线程明明是空闲的,为什么仍然 ANR?3 个真实 Trace 的证据链复盘
android
张元清1 小时前
React useSessionStorage Hook:刷新不丢、只属于当前标签页的状态 (2026)
前端·javascript·react.js
weixin_BYSJ19871 小时前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
xiaominlaopodaren1 小时前
three.js最小地图运行时(一):视图状态
javascript·gis·three.js