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

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

相关推荐
Highcharts.js3 小时前
Highcharts漏斗图表使用配置指南
java·开发语言·javascript·信息可视化·highcharts·漏斗图
武昌库里写JAVA7 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
Pniubi7 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
Lanwarf-前端开发8 小时前
Vue3 + Canvas/WebGL 雷达扫描可视化实战:PPI、RHI、VOL、SVOL 四种模式原理与实现
前端·javascript·vue.js·webgl
FungLeo10 小时前
FengCMS · PHP+MySQL 升级实录 · 危险默认值之殇:root/123456、认证码 8888 写进配置加载器
android·mysql·php·安全加固·fengcms
yz_aiks10 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
YIAN11 小时前
从 LangChain 到 DeepAgents:手把手拆解 createAgent、Middleware 与复杂 Agent
javascript·langchain·deepseek
冬夜Zis12 小时前
顺着作用域链和 outer 指针,一次性看懂闭包底层逻辑
javascript
Ceelog12 小时前
Mac 上怎么找出并安全清理旧的 node_modules?(实测 304 个占 66.3 GB)
javascript
小码哥06813 小时前
智慧物业系统源码定制:公告发布范围与住户阅读记录设计
前端·javascript·vue.js·物业管理·物业系统·物业软件