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

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

相关推荐
我不会插花弄玉5 分钟前
8. 复合查询【由浅入深-MySQL】
android·数据库·mysql
熊文豪8 分钟前
机器人开发者生态分析:行业分工变化与启元的定位
android·机器人·启元机器人
郑州光合科技余经理1 小时前
同城商城源码:商品库和订单库怎么随包交付
android·java·开发语言·后端·uni-app·php·ai编程
Eastmount2 小时前
[论文阅读] (54)NDSS26 JSIMPLIFIER:动静态与LLM如何协同完成JavaScript解混淆?
javascript·论文阅读·恶意代码分析·智能体安全·ndss
蒸鱼Yuzheng2 小时前
移动游戏功耗与能效归因:帧率、画质、温控和续航如何一起评估
android·性能测试·功耗优化·游戏性能·温控
Ai-_Man2 小时前
ChatGPT还是不可以导出左侧所有对话,只能点进去单条内容导出,方法不对吗?
开发语言·javascript·人工智能·chatgpt·小程序·ecmascript
miofly2 小时前
GitHub 今日推荐|security-audit-skill:让编码代理自己审计漏洞还互相验证
javascript·开源·github
hai_android3 小时前
Android 设备锁定:Kiosk Mode 实战
android·java·android jetpack
এ慕ོ冬℘゜3 小时前
es6理论总结
前端·javascript·es6