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

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

相关推荐
只睡四小时14 分钟前
LoAF 归因:原生 JS 每次输入 201 次布局读取
开发语言·javascript·性能优化·ecmascript·甘特图·前端性能·loaf
灯澜忆梦14 分钟前
拓扑排序(Kahn BFS)| LeetCode 210 课程表 II
算法·leetcode·排序算法·宽度优先
冰暮流星16 分钟前
mysql之触发器
android·数据库·mysql
风早爽太24 分钟前
Android 学习笔记:纯代码实现 TabLayout
android·kotlin
Meteors.1 小时前
Android 项目常见问题与 23 种设计模式应用对照表(含 Kotlin 示例)
android·设计模式·kotlin
妮妮分享1 小时前
定位坐标偏移几百米?GCJ-02 / WGS84 / BD-09 坐标系踩坑实录(JS 附代码)
开发语言·javascript·坐标系转换·wgs84·gcj02
xcLeigh1 小时前
Go入门:逻辑运算符与短路求值机制
android·java·golang·go·教程
map_3d_vis1 小时前
百度地图信息窗口 InfoWindow 与自定义样式(JSAPI 4.0)
前端·javascript·地图·百度地图
Nuanyt2 小时前
LeetCode Hot 100 贪心算法专题 121 / 55 / 45 / 763 (Java)
java·算法·leetcode·贪心算法·dp
楚识科技2 小时前
移动端 OCR SDK 集成拆解:Android/iOS 离线识别与结构化回填
android·ios·ocr