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

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

相关推荐
Dxy12393102165 小时前
MySQL索引完整教程:创建、查看、修改、删除与日常管理
前端·javascript·mysql
端庄的战斗机7 小时前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
机智的张尼玛9 小时前
我基于 Kotlin Multiplatform 实现了一套跨平台的弱网离线同步引擎
android·开源·kotlin
前端毕业班9 小时前
uni-app 小程序支持 teleport 了
前端·javascript·vue.js
东风破_10 小时前
LLM 为什么记不住你?无状态、messages 和上下文管理
javascript·人工智能
Hilaku11 小时前
前端架构师的克制:什么时候该坚决对新技术说不?
前端·javascript·程序员
古夕11 小时前
多应用同域部署下 Favicon 异常问题排查与治理
前端·javascript
逗逗豆巴吧11 小时前
WPS 加载项中实现当前文档直接上传
前端·javascript·ecmascript 6
妙码生花11 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(二十一):网络请求封装优化
前端·javascript·vue.js
用户114818678948411 小时前
普通Fetch、Fetch流式、Axios、SSE:谁才是流式输出的正确操作?
前端·javascript