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

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

相关推荐
EveryPossible11 分钟前
静态箭头连线
开发语言·javascript·ecmascript
伍哥的传说12 分钟前
QRCode React 完全指南:现代化二维码生成解决方案
前端·javascript·react.js·qrcode.react·react二维码生成·qrcodesvg·qrcodecanvas
listhi52021 分钟前
Map对象在JavaScript循环中的使用
开发语言·前端·javascript
·云扬·2 小时前
【Leetcode hot 100】101.对称二叉树
算法·leetcode·职场和发展
睡不醒的kun7 小时前
leetcode算法刷题的第三十二天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
sun0077008 小时前
android ndk编译valgrind
android
雾恋8 小时前
最近一年的感悟
前端·javascript·程序员
华仔啊8 小时前
Vue3 的 ref 和 reactive 到底用哪个?90% 的开发者都选错了
javascript·vue.js
A黄俊辉A9 小时前
axios+ts封装
开发语言·前端·javascript
AI视觉网奇9 小时前
android studio 断点无效
android·ide·android studio