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

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

相关推荐
核电机组16 小时前
flutter集成到Android混合开发
android·flutter
创业之路&下一个五年17 小时前
JS编程范式 \& 面向对象范式
开发语言·前端·javascript
李白你好17 小时前
DesJsFinder被动JS分析 + 框架识别 + 主动Fuzz + 响应指纹 — 红队API挖掘利器
javascript
ct97817 小时前
Axios 请求取消
前端·javascript·vue.js
怕浪猫17 小时前
Electron 开发实战(九):调试技巧与开发者工具|测试、性能分析、日志追踪全解
前端·javascript·electron
智能制造产品经理代码提升17 小时前
ES6+ 标准使用手册
前端·javascript·es6
恋猫de小郭17 小时前
Android 17 内存管理将严格管控,App 要注意适配
android·前端·flutter
赏金术士17 小时前
Android 组件化学习项目(Kotlin + AGP8+)
android·学习·kotlin
问心无愧051317 小时前
ctf show web入门100
android·ide·笔记·android studio