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

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

相关推荐
Lesile4 小时前
Interview#1 历史演进:MVC · MVP · MVVM · MVI架构详解
android·android jetpack
windliang4 小时前
Claude Code 源码分析(一):从 claude 命令到 Agent 主循环
javascript·面试·ai编程
申君健24864182772024 小时前
WebGPU 内部运行原理:Format、Texture 与 GPU 侧到底在干什么
javascript
JoyT5 小时前
Nuxt 3的核心设计与静态官网应用
前端·javascript·vue.js
杉氧5 小时前
Flutter 像素级还原实战:用 CustomPaint 与 Bezier 曲线手绘精致图针
android·前端·flutter
白白白小纯6 小时前
算法篇—返回倒数第k个节点
c语言·数据结构·算法·leetcode
张元清7 小时前
React useDropZone Hook:搭建一个文件拖放区(2026)
javascript·react.js
思码梁田7 小时前
CSS 定位详解:从相对到固定,掌握网页布局的核心
前端·javascript·css
软件开发技术深度爱好者7 小时前
HTML5实现数学函数画图器
前端·javascript·html5
我命由我123457 小时前
Android 在构建过程中,发现有两个依赖库都包含了相同路径的资源文件
android·java·开发语言·java-ee·kotlin·android-studio·android runtime