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

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

相关推荐
用户83134859306986 分钟前
Vue3 v-for:常用用法与开发高频坑点
前端·javascript·vue.js
2603_9658966223 分钟前
CSS BEM 命名规范|组件化样式分层权威指南
前端·javascript·css
凯瑟琳.奥古斯特1 小时前
力扣1015C++解法技巧
c++·算法·leetcode·链表·职场和发展
文丑颜不良啊1 小时前
LeetCode626~650题目解析
java·leetcode
忆挽篱笙歌1 小时前
进程替换函数与shenll命令行解释器
前端·javascript·算法
小冯不疯2 小时前
688 / 拼多多 / 淘特三类供货链路:从采购单到应付凭证的 4 段对账
javascript
moshuying2 小时前
DeppInfer系列之 - 矩阵、注意力与 GPU:拆解 DeepGEMM 与 FlashMLA
前端·javascript·面试
文丑颜不良啊2 小时前
LeetCode601~625题目解析
java·leetcode
事圆则缓2 小时前
Android 性能排查实战:怎么看内存抖动、CPU 占用和 FPS
android
文丑颜不良啊2 小时前
LeetCode651~675题目解析
java·leetcode