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

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

相关推荐
草履虫建模8 分钟前
力扣算法 121. 买卖股票的最佳时机
算法·leetcode·职场和发展·贪心算法·动态规划·一次遍历
爱尔兰极光13 分钟前
LeetCode--有序数组的平方
算法·leetcode·职场和发展
haluhalu.32 分钟前
LeetCode---基础算法刷题指南
数据结构·算法·leetcode
iAkuya38 分钟前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
2601_9498333944 分钟前
flutter_for_openharmony口腔护理app实战+知识实现
android·javascript·flutter
晚霞的不甘1 小时前
Flutter for OpenHarmony从基础到专业:深度解析新版番茄钟的倒计时优化
android·flutter·ui·正则表达式·前端框架·鸿蒙
东东5161 小时前
果园预售系统的设计与实现spingboot+vue
前端·javascript·vue.js·spring boot·个人开发
起风的蛋挞1 小时前
Matlab提示词语法
前端·javascript·matlab
爱尔兰极光1 小时前
LeetCode--移除元素
算法·leetcode·职场和发展
鸟儿不吃草1 小时前
android的Retrofit请求https://192.168.43.73:8080/报错:Handshake failed
android·retrofit