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

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

相关推荐
过期动态3 小时前
【LeetCode 热题 100】移动零
java·数据结构·算法·leetcode·职场和发展·rabbitmq
rocpp3 小时前
Android 相册选择与拍照接入实践:MediaStore 分页、权限适配与 FileProvider
android
zithern_juejin4 小时前
new 运算符
javascript
前端毕业班4 小时前
uniapp web 灵活控制 style scoped
前端·javascript·vue.js
Flynt4 小时前
升级Flutter 3.44,我踩了HCPP和AGP 9的坑
android·flutter·dart
张元清5 小时前
在 React 里写动画又不跟渲染周期较劲:useRafFn、useRafState、useFps、useDevicePixelRatio、useUpdate
前端·javascript·面试
白色牙膏5 小时前
Cocos Creator 2.4.x 接入 AdMob 插件的迁移实践
android
菜菜的顾清寒5 小时前
力扣HOT100(32)二叉树的中序遍历
数据结构·算法·leetcode
csdn_aspnet6 小时前
java 算法 LeetCode 编号 70 - 爬楼梯
java·开发语言·算法·leetcode
甜味弥漫6 小时前
JavaScript 底层逻辑:从内存视角看原型与原型链
前端·javascript