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

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

相关推荐
好的佩奇11 小时前
Dart 之 JSON
android·flutter·dart
_祝你今天愉快12 小时前
Android 事件传递机制:[一] 事件分发机制详解
android
FYKJ_201014 小时前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
kyriewen14 小时前
我测了 5 种关页上报,两种老写法一条都没发出去
前端·javascript·程序员
旖旎夜光16 小时前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
Digitally17 小时前
如何将电脑上的联系人传输到安卓手机(4 种方法)
android
天若有情67319 小时前
开源|纯前端·条码&二维码在线生成器,支持拖拽缩放、复制生成码图片
前端·javascript·开源·html·二维码·条形码
map_vis_3d20 小时前
控制百度地图视野:setCenter、setZoom、panTo、flyTo 和 setViewport
前端·javascript·地图·百度地图
木井巳21 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
Hilaku21 小时前
前端到底要不要写单元测试?
前端·javascript·程序员