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

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

相关推荐
mmsx24 分钟前
Android APK 加固方案怎么落地:从加壳到校验的组合取舍
android·网络·安全·签名
西红柿炖牛腩35441 分钟前
机房电脑不能联网,怎么离线把课件里的 3D 模型压小?Draco / Meshopt 参数清单
前端·javascript·3d·性能优化·大屏端
爱喝水的小周42 分钟前
实验十三 Vue 过渡与动画—电商后台消息中心实现
前端·javascript·vue.js
hunterandroid1 小时前
Navigation Component 工程落地:从单 Activity 架构到深度链接配置
android·前端
无责任此方_修行中1 小时前
如何不用括号调用 JS 的函数?
前端·javascript·node.js
撩得Android一次心动1 小时前
Jetpack Compose 知识点整理3【个人用】
android·笔记·学习·kotlin·android compose
无责任此方_修行中1 小时前
Deno 的八年:一场没逃出 Node 引力的运行时起义
前端·javascript·node.js
Kapaseker1 小时前
别再只会写 <T>:Kotlin 泛型的实战用法
android·kotlin
FlightYe2 小时前
音视频修炼之容器与协议(一):MP4和MOV的box剖析
android·linux·c++·ffmpeg·音视频