[路飞]_每天刷leetcode_18(化栈为队 Implement Queue Using Stacks)

436 阅读2分钟

化栈为队

LeetCode传送门 面试题 03.04. Implement Queue using Stacks LCCI

题目

实现一个MyQueue类,该类用两个栈来实现一个队列。

Implement a MyQueue class which implements a queue using two stacks.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // return 1
queue.pop();   // return 1
queue.empty(); // return false

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

思考线


解题思路

这道题的关键是如何用栈来模拟队列。 我们知道栈的特点是FILO(先进后出),而队列的特点是FIFO(先进先出),那么我们如果让栈A中的元素pop时全部push到另一个栈B里,那么栈B相对于栈A就是队列了。

我们根据这个思路来完成代码。

我决定在MyQueue执行push的时候用一个变量temp来保存push进来的值, 我们用 this.queue这个栈来实现队列的操作。那么在执行push操作我们来检查一下this.queue是否有值,若有值,则全部pop出来,并且用 temp来接收。然后再用temp去接收要push的元素。最后在执行一遍上面操作的反向操作,让 temp中的全部元素都pop出去,并用this.queue来接收。则我们完成从栈到队列的转化。

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

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function () {
    return this.queue.pop();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    return this.queue[this.queue.length -1];
};

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

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

我们再用ES6的 Class语法来实现一遍。

class MyQueue {
    constructor() {
        this.queue = [];
    }
    peek() {
        return this.queue[this.queue.length - 1];
    }
    empty() {
        return this.queue.length === 0
    }
    pop() {
        return this.queue.pop();
    }
    push(item) {
        const temp = []
        while (this.queue.length) {
            temp.push(this.queue.pop())
        };
        temp.push(item)
        while (temp.length) {
            this.queue.push(temp.pop())
        }
    }
}

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。