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

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

相关推荐
Escalating_xu9 小时前
【MySQL】事务管理(上):从 ACID 到提交回滚,把一次转账真正做完整
android·数据库·mysql
StarsGreen14 小时前
dumpsys gfxinfo数据信息分析方法
android
好的佩奇15 小时前
蓝牙之 GATT 数据模型
android·flutter·蓝牙
Android小码家16 小时前
Systemui和Launcher是如何无限重启
android·framework
snow@li16 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
夕水19 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript
时间的情敌20 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
GY-9321 小时前
【Android】WorkManager
android
光影少年21 小时前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
bai2731 天前
主线程里 foo 和 FOO 是同一个变量,Worker 里就成了两个:Windows 上 process.env 的大小写边界
javascript·后端