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

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

相关推荐
程序员大阳7 小时前
副队长Vue3教程(2)--Vite 搭建 Vue 项目,认识目录结构
前端·javascript·vue.js·vite·创建项目·目录结构·项目结构
_祝你今天愉快9 小时前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋9 小时前
Android 工程师的技术信仰崩塌史
android
北城笑笑10 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
Patrick_Wilson10 小时前
构建通过了,为什么有些浏览器还会白屏?
前端·javascript·浏览器
ashiho11 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
AirDroid_cn11 小时前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android
Mr_万能胶12 小时前
官方发布,不烧心的 AOSP 编译提速技巧
android·ci/cd·架构
booboosui13 小时前
安卓 8.1 也能装了:代价是一条黄字和两个静默 bug
android
AI前端工程狮13 小时前
我把 MCP 长任务拆成三个工具,token 账单涨了 7 倍
javascript·人工智能·程序员