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

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

相关推荐
天才少年曾牛1 分钟前
【无标题】
android·frameworks
2601_9495758612 分钟前
Flutter for OpenHarmony二手物品置换App实战 - 自定义组件实现
android·javascript·flutter
、BeYourself12 分钟前
动作栏 (ActionBar) 与工具栏 (Toolbar) 的基本使用
android·android-studio
object not found14 分钟前
基于uniapp开发小程序自定义顶部导航栏状态栏标题栏
前端·javascript·小程序·uni-app
zfoo-framework22 分钟前
kotlin
android·开发语言·kotlin
客卿12330 分钟前
力扣二叉树简单题整理--(包含常用语法的讲解)
算法·leetcode·职场和发展
能源革命30 分钟前
Three.js、Unity、Cesium对比分析
开发语言·javascript·unity
We་ct35 分钟前
LeetCode 28. 找出字符串中第一个匹配项的下标:两种实现与深度解析
前端·算法·leetcode·typescript
峥嵘life39 分钟前
Android16 EDLA【CTS】CtsNetTestCases存在fail项
android·java·linux·学习·elasticsearch
血小板要健康41 分钟前
118. 杨辉三角,力扣
算法·leetcode·职场和发展