栈与队列 - 用栈实现队列

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()
 */
相关推荐
你的人类朋友4 小时前
【Node&Vue】JS是编译型语言还是解释型语言?
javascript·node.js·编程语言
烛阴4 小时前
TypeScript高手密技:解密类型断言、非空断言与 `const` 断言
前端·javascript·typescript
样子20185 小时前
Uniapp 之renderjs解决swiper+多个video卡顿问题
前端·javascript·css·uni-app·html
黑客飓风5 小时前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
YeeWang8 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip8 小时前
Jenkins部署前端项目实战方案
前端·javascript·架构
Orange3015118 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
李明卫杭州9 小时前
CSS `clamp()` 函数详解
javascript
奶丝兔蜜柚10 小时前
栈溢出优化
javascript
小高00710 小时前
📈前端图片压缩实战:体积直降 80%,LCP 提升 2 倍
前端·javascript·面试