面试题 03.04. 化栈为队

66 阅读1分钟

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


queue.push(1);
queue.push(2);
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false
  • 准备两个栈,一个in栈,处理push逻辑,一个out栈,处理pop逻辑
    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 () {
    if (this.outStack.length) {
        return this.outStack.pop()
    }
    while (this.inStack.length) {
        this.outStack.push(this.inStack.pop())
    }
    return this.outStack.pop()
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    if (this.outStack.length) {
        return this.outStack[this.outStack.length - 1]
    }
    while (this.inStack.length) {
        this.outStack.push(this.inStack.pop())
    }
    return this.outStack[this.outStack.length - 1]
};

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