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

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

相关推荐
用户2986985301416 分钟前
前端实战:在 React 中使用 JavaScript 一键导出 Excel 图表与形状为图片
javascript·react.js·excel
weixin_BYSJ198738 分钟前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php
糖果店的幽灵39 分钟前
【langgraph 从入门到精通graphApi 篇】Command 与动态流程控制
android·java·数据库·人工智能·langgraph
半个落月1 小时前
Vue 3 如何接住大模型的流式回答:从 ReadableStream 到可靠的 SSE 解析
前端·javascript·人工智能
Android-Flutter1 小时前
Android的http和https知识点
android·http·https
Kapaseker1 小时前
Sequence 一定比 List 快?等等,我们先从基础讲起
android·kotlin
tkevinjd2 小时前
力扣72-编辑距离
算法·leetcode·职场和发展
晓得迷路了2 小时前
栗子前端技术周刊第 138 期 - NestJS 12、Astro 7.1、npm 12...
前端·javascript·nestjs
AI刀刀2 小时前
deepseek 内容粘贴后符号丢失怎么办?AI 导出鸭实测解决排版乱码问题
android·人工智能·excel·ai导出鸭
东方佑2 小时前
Per-Group 混合精度量化:将 14B 视频生成模型压缩至 11 GB
android