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

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

相关推荐
道尔柯南15 分钟前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
唐诺1 小时前
5、Android JNI 动态注册中的“签名“详解
android·jni
Dream it possible!3 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊3 小时前
算法之双指针系列(一)
算法·leetcode
zhaoshuzhaoshu4 小时前
Android 系统启动与调试中的日志抓取方式全解析
android
Pniubi5 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
雨声不在5 小时前
android 动画掉帧
android
Pniubi6 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
在多学一点6 小时前
MYSQL第二次作业
android·数据库·mysql
骑着蜗牛撵大象3277 小时前
MySQL 8.0 迁移后 SQL 变慢:执行计划里 3 类被忽略的成本差异
android·数据库·sql·mysql·优化器·执行计划