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

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

相关推荐
重生之后端学习16 分钟前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展
水獭比特33 分钟前
工作流都公开了,为什么还不能继承 Owner 权限?
javascript·人工智能·node.js
程序员-Benothing1 小时前
MySQL 索引下推是什么?——深入理解 ICP 原理与实践
android·数据库·mysql
怀化纱厂球迷1 小时前
百度地图--android接入百度地图导航
android
AFinalStone2 小时前
Android 7系统无障碍服务(四)AccessibilityEvent 的产生与投递
android·无障碍服务
智购科技无人售货机工厂2 小时前
2026自动售货机热敏打印模块集成:从串口驱动到小票自动裁切的工程实践~YH
android·stm32·单片机·嵌入式硬件·系统架构
ly76893 小时前
Vue 3 从入门到工程实践:基础语法、组件化、路由、状态管理与项目部署
前端·javascript·vue.js
A13345553 小时前
苹果安卓手机播放器推荐:2026无广告4K怎么选
android·智能手机
四千岁3 小时前
抓包LangChain-了解LangChain的原理
前端·javascript·后端
用户298698530144 小时前
使用 JavaScript 在 React 中实现 Word 转 PDF
前端·javascript·react.js