【算法11天:Day11】第五章栈和队列 LeetCode 用栈实现队列(232)

79 阅读1分钟

题目一:

image.png

解法一:(双队列)

解题思路:使用栈来模拟队列的行为,如果仅仅用一个栈,肯定是不行的,所以需要使用两个栈,一个输入栈stackIn,一个输出栈stackOut。push数据的时候,只要数据放入输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。 最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。


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() {
    if (this.stackOut.length) {
        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()
 */

解法二:(不使用栈,使用数组,不题目要求不符)


/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.arr = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    // this.arr.push(x);
    this.arr[this.arr.length] = x
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    // return this.arr.shift() ;
    let [a, ...newArr] = this.arr;
    this.arr = newArr;
    return a;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.arr[0];
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    if(this.arr.length == 0) return true;
    return false;
};