[路飞]_前端算法第三十七弹-面试题 03.04. 化栈为队

209 阅读2分钟

示例:

MyQueue queue = new MyQueue();

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

说明:

  • 你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

首先我们要了解栈和队列的区别

  • 队列:先进先出
  • 栈:后进先出

了解了这个之后,就需要考虑,栈的push方法会向栈顶添加元素

stack=[];
stack.push(1);
stack.push(2);
stack=[1,2]

而我们需要模拟一个队列queue

queue=[];
queue.push(1);
queue.push(2);
queue=[2,1]

因为每次stack只能取出栈顶元素,所以,我们还需要一个栈去将原有的栈翻转

inStack=[1,2,3]
outStack.push(inStack.pop())
这样再通过遍历
outStack=[3,2,1]

而pop方法,是取出栈顶元素,现在要使用队列的pop方法,那就是取出队列的第一个元素。

我们可以将inStack置换到outStack中,但是只留最后一个元素,也就是先入的那个元素,记为ans. 之后我们再将outStack中的元素反置换回inStack中。ans便是queue的pop()的元素。

对于peek方法,只需将pop方法的ans元素,在outStack之前入栈到inStack中即可。

而empty不需要知道队列内的顺序,只需要确定队列的长度即可。

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

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function () {
    while (this.inStack.length > 1) {
        this.outStack.push(this.inStack.pop())
    }
    let ans = this.inStack.pop();
    while (this.outStack.length > 0) {
        this.inStack.push(this.outStack.pop())
    }
    return ans
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    while (this.inStack.length > 1) {
        this.outStack.push(this.inStack.pop())
    }
    let ans = this.inStack.pop();
    this.inStack.push(ans)
    while (this.outStack.length > 0) {
        this.inStack.push(this.outStack.pop())
    }
    return ans
};

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