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

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

相关推荐
Penge6661 小时前
《Go 后端开发者学 React:useState》
javascript
Penge6661 小时前
《Go 后端开发者学 React:数据渲染》
javascript
ikoala4 小时前
AI 写页面像说明书,修 Bug 像贴膏药?把这两句话写进 AGENTS.md
前端·javascript·ai编程
Penge6664 小时前
《Go 后端开发者学 TypeScript:ES Module了解》
javascript
Penge6665 小时前
《Go 后端开发者学 TypeScript:从零搭建与运行》
javascript
好的佩奇5 小时前
Dart 之扩展方法
android·flutter·dart
Penge6666 小时前
《Go 后端开发者学 TypeScript:keyof关键字》
javascript
Penge6666 小时前
《Go 后端开发者学 TypeScript:extends关键字》
javascript
张张123y6 小时前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
三少爷的鞋7 小时前
换个思路理解:非阻塞挂起
android