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

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

相关推荐
万少3 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童6 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
先吃饱再说7 小时前
JavaScript中`this` 的“千层套路”:从默认绑定到箭头函数的五种指向
javascript
CYY957 小时前
Compose 入门篇
android·kotlin
foxire7 小时前
基于nodejs实现服务端内核引擎
javascript
触底反弹10 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
free3510 小时前
AST Interpreter 的设计:为什么分 evaluate() 和 execute()
javascript
等咸鱼的狸猫10 小时前
JavaScript 隐式类型转换:从入门到精通
javascript
杉氧10 小时前
Compose 时代的 MVI 架构:如何用单向数据流驱动复杂 UI?
android·架构·android jetpack
杉氧11 小时前
Modifier 的艺术:为什么链式调用的顺序决定了UI 的生命周期?
android·架构·android jetpack