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

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

相关推荐
敲代码的瓦龙12 分钟前
Jetpack?lifecycle!!!
android·kotlin
苦瓜花18 分钟前
Hilt用使用及原理
android
Xin77029 分钟前
LeetCode 46. 全排列(回溯法)
leetcode
深度学习04071 小时前
MySQL InnoDB Cluster 部署完整文档
android·mysql·adb
鬼手点金1 小时前
单轮对话:最简单的 API 调用
java·服务器·前端·javascript·react.js·servlet·tomcat
罗丹丹Luna2 小时前
JavaScript计算任务峰值并发:同一时刻先结束还是先开始
javascript
邪修king2 小时前
Re:Linux系统篇(三十七):进程间通信Chapter4:System V 共享内存深度解析:为什么它是最快的 IPC?
android·linux·运维
古夕2 小时前
同样的 font-weight,为什么这个项目的字体就是更细?
前端·javascript
用户337922545682 小时前
Kiora SDK:在 Android 上组织端侧模型、工具与 A2A 协作
android
文丑颜不良啊2 小时前
LeetCode476~500题目解析
java·leetcode