栈与队列 - 用栈实现队列

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()
 */
相关推荐
再学一点就睡1 小时前
双 Token 认证机制:从原理到实践的完整实现
前端·javascript·后端
幻灵尔依2 小时前
前端编码统一规范
javascript·vue.js·代码规范
前端小巷子2 小时前
JS 实现图片瀑布流布局
前端·javascript·面试
杜蒙2 小时前
React Hooks 详解
前端·javascript
小菜全3 小时前
Vue 3 + TypeScript 事件触发与数据绑定方法
前端·javascript·vue.js
Hilaku3 小时前
面试官开始问我AI了,前端的危机真的来了吗?
前端·javascript·面试
zheshiyangyang3 小时前
TypeScript学习【一】
javascript·学习·typescript
β添砖java4 小时前
案例二:登高千古第一绝句
前端·javascript·css
TNTLWT4 小时前
单例模式(C++)
javascript·c++·单例模式
落日沉溺于海5 小时前
React From表单使用Formik和yup进行校验
开发语言·前端·javascript