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

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

相关推荐
程序猿追7 分钟前
返库看板最小化后还会刷新吗?HarmonyOS 7 窗口状态实测
android·开发语言·kotlin·harmonyos
奶龙无翅何谈飞19 分钟前
从手机输入到 Windows 进程退出码,拆解 Code Link 的远程终端链路
android·windows·adb·蓝牙·开发工具
xixiaoyunya33 分钟前
MySQL 单表备份:从手动导出到定时自动化的完整实践
android·mysql·自动化
SEO_juper38 分钟前
PHP 站内搜索词分析器:从买家搜的词里,挖出内容缺口
前端·javascript·node.js·json·1024程序员节
Rain的Java大神之路43 分钟前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
2501_915921431 小时前
iOS 上架 App Store 常见 ITMS 报错排查,哪些需要修改哪些是警告
android·ios·小程序·https·uni-app·iphone·webview
徐同保1 小时前
一个 HTML 属性顶替三行 JS:`inert` 的正确用法
前端·javascript·html
默 语1 小时前
【HarmonyOS7】ArkTS通用属性实战(一):一文吃透尺寸设置 width/height/size
android
开发者导航2 小时前
Cursor plugins 插件仓库上手:结构解析与安装使用教程
android·linux·ubuntu·ai·typescript·cursor·插件开发
map_3d_vis2 小时前
百度地图画圆 Circle 和矩形 Rectangle(JSAPI 4.0)
前端·javascript·gis·地图·百度地图