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

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

相关推荐
圣保罗的大教堂23 分钟前
leetcode 453. 最小操作次数使数组元素相等 中等
leetcode
椒哥27 分钟前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
五彩小白1 小时前
喵呜打卡项目总结
android·团队开发
kyriewen1 小时前
我测了 6 种防请求竞态的写法:只有 1 种真能打
前端·javascript·程序员
OpsEye2 小时前
企业大模型压测,需要重点关注哪些指标?
javascript·ai编程
古法安卓2 小时前
Android-GPU压测工具
android·java·android studio
像我这样帅的人丶你还2 小时前
我html生成的doc文档为何在手机文档显示不了图片?
前端·javascript
Tisfy4 小时前
LeetCode 0453.最小操作次数使数组元素相等:两次遍历(反向思维)
算法·leetcode·题解·遍历·反向思维
xcLeigh4 小时前
KingbaseES数据库教程:初识数据库,从安装到跑通第一条SQL
android·数据库·sql·安装·数据库教程·kes
君万4 小时前
【LeetCode每日一题】回溯:46. 全排列 78. 子集 39. 组合总和
算法·leetcode·go