Leetcode刷题(第232题)——用栈实现队列

x33g5p2x  于2022-03-17 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(297)

一、题目

二、示例

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

三、思路
本题可以使用双栈来解决问题。
四、代码

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

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    while(this.stack.length > 1) {
        this._stack.push(this.stack.pop())
    }
    let cur = this.stack.pop()
    while(this._stack.length > 0) {
        this.stack.push(this._stack.pop())
    }
    return cur
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.stack[0]
};

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

/**
 * 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()
 */

五、总结

相关文章