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

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

相关推荐
李斯维6 小时前
从历史的角度看 Android 软件架构
android·架构·android jetpack
kyriewen7 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
plainGeekDev9 小时前
Activity 间传值 → Navigation 参数
android·java·kotlin
用户41659673693559 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
plainGeekDev9 小时前
onActivityResult → ActivityResult API
android·java·kotlin
minglie13 小时前
一个置换问题
javascript
默_笙13 小时前
🌀 别再手动写 Prompt 了!我让 AI 自己循环改到满意为止
javascript
随遇丿而安13 小时前
第10周:Activity 基础功能与生命周期优化
android
To_OC1 天前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
alexhilton1 天前
Android车载OS中的Remote Compose
android·kotlin·android jetpack