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

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

相关推荐
君君思密达2 小时前
LeetCode Hot 100 题目详解-滑动窗口
算法·leetcode·职场和发展
万少11 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
fqq311 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
小爬的老粉丝13 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
半夏微凉半夏殇13 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
满栀58514 小时前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
阿pin15 小时前
Android随笔-kotlin withContext
android·kotlin·withcontext
树码小子16 小时前
开启 IDEA 中的断言功能
android·java·intellij-idea
Kslient16 小时前
HeaderBehavior
android
大龄码农有梦想16 小时前
Vue + BPMN.js + Camunda:搭建企业级流程设计器完整实践
javascript·vue.js·流程设计器·bpmn.js·bpmn·流程审批·工作流设计器