栈与队列 - 用栈实现队列

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()
 */
相关推荐
雾恋3 小时前
最近一年的感悟
前端·javascript·程序员
华仔啊3 小时前
Vue3 的 ref 和 reactive 到底用哪个?90% 的开发者都选错了
javascript·vue.js
A黄俊辉A4 小时前
axios+ts封装
开发语言·前端·javascript
小李小李不讲道理4 小时前
「Ant Design 组件库探索」四:Input组件
前端·javascript·react.js
郑板桥305 小时前
tua-body-scroll-lock踩坑记录
前端·javascript
解道Jdon6 小时前
SpringBoot4与Spring7发布:云原生深度进化
javascript·reactjs
gnip7 小时前
pnpm 的 monorepo架构多包管理
前端·javascript
zolty7 小时前
基于hiprint的票据定位打印系统开发实践
javascript
百思可瑞教育8 小时前
使用UniApp实现一个AI对话页面
javascript·vue.js·人工智能·uni-app·xcode·北京百思可瑞教育·百思可瑞教育
Enddme9 小时前
《前端笔试必备:JavaScript ACM输入输出模板》
前端·javascript·面试