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

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

相关推荐
草莓熊Lotso1 分钟前
MySQL 索引特性与性能优化全解
android·运维·数据库·c++·mysql·性能优化
Kapaseker2 分钟前
千万不要以为你搞懂了 var 和 val
android·kotlin
老虎06279 分钟前
LeetCode热题100 刷题笔记(第五天)多维动态规划(中心扩展法) 「 最长回文子串」
笔记·leetcode·动态规划
盐水冰10 分钟前
【WEB模型】CS架构&BS架构&HTML&CSS&JS
开发语言·前端·javascript
阿凤2110 分钟前
js文件怎么引入到vue3的项目中
开发语言·前端·javascript·vue.js
TE-茶叶蛋12 分钟前
安卓应用(uniapp开发)分享微信-申请appid
android·微信·uni-app
Q741_14718 分钟前
每日一题 力扣 2751.机器人碰撞 映射 模拟 栈 C++ 题解
算法·leetcode·模拟··映射
大白要努力!19 分钟前
Android libVLC 3.5.1 实现 RTSP 视频播放完整方案
android·java·音视频
AirDroid_cn29 分钟前
手机上看的网页,怎样自动在荣耀 MagicOS 10 平板上接着打开?
android·智能手机·电脑·荣耀手机