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

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

相关推荐
且随疾风前行.几秒前
Paint Cavans高级绘制:[一]Paint画笔高级应用
android·ui
咩咩啃树皮43 分钟前
JavaScript 异步流程为什么容易失控?从回调到可维护设计
开发语言·javascript·ecmascript
郑州光合科技余经理2 小时前
同城小程序开发:同一笔单在用户端和商家端各显示到哪
android·java·开发语言·前端·后端·uni-app·php
zzppff1p2 小时前
用AI写了个小游戏
前端·javascript
普通人63 小时前
uniapp模版JS
开发语言·javascript·小程序·uni-app·1024程序员节
KumaoHub3 小时前
棋牌游戏开发中聊天文本的长度限制与安全显示
javascript
pigdreams3 小时前
Google 官方 Android CLI:让AI直接读布局结构而不是用adb截图验证
android·人工智能·adb
G018_star sky♬3 小时前
nodeJS他是如何用JavaScript封装C++的呢
开发语言·javascript·c++
wiseyao12193 小时前
uniapp scroll-view滚动到最后
前端·javascript·uni-app
怕浪猫3 小时前
Step 5 Preview 模型写 3D 象棋,两个小时上线
前端·javascript·面试