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

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

相关推荐
兰亭妙微UI设计公司1 小时前
兰亭妙微ui设计公司分享:B端组件命名如何支持团队协作
前端·javascript·vue.js
方白羽1 小时前
Android 双开环境底层剖析与风控检测落地
android·安全·app
weixin_563371472 小时前
Android Studio 2024 版 Device Explorer 打开方法
android·ide·android studio
小大宇2 小时前
Vue知识点-ElementPlus-03提示框+询问+通知
前端·javascript·vue.js
j7~3 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
前端技术官3 小时前
前端的技术判断力是怎么练出来的?
javascript·web前端·localstorage·debounce·弱网处理
Shaoshing4 小时前
LeetCode100 42.接雨水
java·算法·leetcode
程序员大阳4 小时前
副队长JavaScript教程(60)-BOM 初识:window 对象与浏览器模型
javascript·bom·window对象·浏览器模型
web打印社区4 小时前
Chrome-kiosk-printing能上生产吗
开发语言·前端·javascript·chrome·websocket
AIsoft_86894 小时前
职场音频文件怎么整理?录音APP有哪些用法
android·音视频