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

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

相关推荐
圣保罗的大教堂42 分钟前
leetcode 3517. 最小回文排列 I 中等
leetcode
kyriewen1 小时前
面试官让我手写虚拟列表——AI生成的版本,快速滚动几下就白屏了
前端·javascript·面试
码农coding2 小时前
android12 systemUI 之锁屏
android
圆山猫2 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
爱笑鱼2 小时前
Binder(七):getCallingUid() 读到的是谁?clearCallingIdentity() 又清掉了什么?
android
alphaTao3 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
许彰午3 小时前
政务督办的分合模式:主办协办的并发审批
前端·javascript·政务
易筋紫容3 小时前
创建型模式:对象的诞生艺术
开发语言·前端·javascript
0_Error_5 小时前
猫国建设者 修改资源 自动采集
javascript
贩卖黄昏的熊5 小时前
NestJS简明教程——安全
开发语言·javascript·安全·typescript·nest.js