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

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

相关推荐
雨白10 小时前
单例设计模式:从 Java/Kotlin 实现到 Android 实战
android
一个游离的指针10 小时前
Vue2:vue-router
前端·javascript·vue.js
凌晨三点说晚安12 小时前
理解 JavaScript 对象、原型与包装类
javascript
凌晨三点说晚安13 小时前
理解 JavaScript 作用域链、return 与闭包
javascript
tryCbest13 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx13 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
LK_0713 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi13 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
Funlang13 小时前
在 Windows 95 上写前端
前端·javascript·windows
文丑颜不良啊14 小时前
LeetCode3341~3360题目解析
java·leetcode