0
点赞
收藏
分享

微信扫一扫

力扣解题 232. 用栈实现队列

19.png 20.png

解法一

设置两个栈, 在pop 和 peek 时, 先把元素倒到另一个栈, 在另一个栈里操作, 然后将另一个栈里元素再倒回来就实现了队列先进先出了。

/*
* @lc app=leetcode.cn id=232 lang=javascript
*
* [232] 用栈实现队列
*/

// @lc code=start

var MyQueue = function () {
    this.arr = [];
};

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

/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
    let brr = [];
    while (this.arr.length) {
        brr.push(this.arr.pop());
    }
    let c = brr.pop();
    while (brr.length) {
        this.arr.push(brr.pop());
    }
    return c;
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
    let brr = [];
    while (this.arr.length) {
        brr.push(this.arr.pop());
    }
    if (brr.length == 0) {
        throw new Error();
    }
    let c = brr[brr.length - 1];
    while (brr.length){
        this.arr.push(brr.pop());
    }
    return c;
};

/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
    return this.arr.length == 0 ? true : false;
};

/**
* 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()
*/
// @lc code=end

解法二 更高效一点

/*
* @lc app=leetcode.cn id=232 lang=javascript
*
* [232] 用栈实现队列
*/

// @lc code=start

var MyQueue = function () {
    // 用两个栈, arr专用入栈。
    this.arr = [];
    // brr专门用来 反转arr元素的。
    this.brr = [];
};

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

/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
    let c = this.peek();
    // 直接将brr栈顶元素弹出。
    this.brr.pop();
    return c;
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
    // 如果brr中仍有数据,那么直接返回brr栈顶元素
    if(this.brr.length > 0){
        return this.brr[this.brr.length -1];
    }
    if(this.arr.length == 0){
        // 如果走到这,说明arr和brrd 都没有数据了
        return -1;
    }
    this.brr = [];
    //arr里面数据 倒给brr。然后将brr栈顶元素返回。
    while (this.arr.length) {
        this.brr.push(this.arr.pop());
    }
    if (this.brr.length == 0) {
        throw new Error();
    }
    let c = this.brr[this.brr.length - 1];
    
    return c;
};

/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
    // 如果arr 和 brr 都没有数据 ,说明队列是空的。
    return this.arr.length == 0 && this.brr.length == 0 ? true : false;
};

/**
* 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()
*/
// @lc code=end
举报

相关推荐

0 条评论