栈与队列 - 用栈实现队列

232. 用栈实现队列


方法一:

javascript 复制代码
var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackIn.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    const size = this.stackOut.length;
    if (size) {
        return this.stackOut.pop();
    }
    while (this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    const x = this.pop();
    this.stackOut.push(x);
    return x;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return !this.stackIn.length && !this.stackOut.length
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */
相关推荐
默_笙43 分钟前
🚅 地铁的"回头路、存档点与人工闸机"(下):LangGraph 的循环、持久化与中断
前端·javascript
flash俊杰1 小时前
Zod Schema 驱动的 IPC 契约:从入参校验到状态机一致性的三层防御
javascript·typescript
一条溺水的鱼3 小时前
一次讲透 JS 原型链 —— prototype、__proto__ 和 constructor 到底啥关系
javascript
三乐2283 小时前
一文搞懂 JS 事件流:捕获、冒泡、事件委托
javascript·html
愛芳芳6 小时前
基于 Electron + Vue3 的仿 PC 微信客户端项目实战
前端·javascript·css·elementui·typescript·electron·vue
阿虎儿6 小时前
论 JavaScript 的怪异之处
javascript
gnip7 小时前
uts 插件示例:获取设备电量信息
前端·javascript
gnip8 小时前
uni-app 原生插件
前端·javascript·uni-app
gnip8 小时前
跨域常用解决方案
前端·javascript
用户298698530148 小时前
前端如何把 TXT 文本文件转成 Word 文档:React 实践
前端·javascript·react.js