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

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

相关推荐
冰暮流星几秒前
javascript之String方法介绍
开发语言·javascript·ecmascript
Hilaku37 分钟前
2026 年前端大洗牌:React 服务端到 Vite 的底层重构
前端·javascript·程序员
名字还没想好☜1 小时前
React setState 连续调用「丢更新」排查:批量更新与函数式更新
前端·javascript·react.js·react·usestate
tachibana21 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
阿pin1 小时前
Android随笔-Retrofit
android·retrofit
come112341 小时前
Vue 2 与 Vue 3 语法区别及使用技巧
前端·javascript·vue.js
想取一个与众不同的名字好难1 小时前
安卓自定义颜色选择器
android
腻害兔1 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:ERP 企业资源模块,一个轻量级进销存的完整实现?
前端·javascript·vue.js·人工智能·前端框架·产品经理·ai编程
糖果店的幽灵2 小时前
langgraph的四种state解析
java·前端·javascript·langgraph
Allshadow2 小时前
Nest.js - 目录结构
javascript·nestjs