[路飞]_LeetCode面试题 03.04. 化栈为队

211 阅读2分钟

题目描述

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

示例:

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 操作)。

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/im… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

队列是先进先出原则,栈是先进后出原则,用两个栈表示一个队列,根据各自的特性,一个用于进队列的栈(pushStack),一个用于出队列的栈(popStack),队列需要pop时保证队列的先进先出原则,需要保证popStack在pop时的元素是pushStack的栈底元素,这样才能符合队列先进先出的特性,所以我们在队列pop时,popStack应该是由popStack.push(pushStack.pop())得来,这样popStack.pop()得到的元素就是队列顶端元素。

题解代码

 * Initialize your data structure here.
 */
var MyQueue = function() {
    this.pushStack = [];//表示队列输入的栈
    this.popStack = [];//表示队列输出的栈
};

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    //队列是先进先出原则,所以当popStack栈为空时,将pushStack栈内容倒叙压进popStack
    //这样popStack在pop时就是优先pop出最开始先进的元素
    if(!this.popStack.length){
        while(this.pushStack.length){
            this.popStack.push(this.pushStack.pop());
        }
    }
    return this.popStack.pop();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(!this.popStack.length){
        while(this.pushStack.length){
            this.popStack.push(this.pushStack.pop());
        }
    }
    //由于peek操作是只显示栈顶元素,并不移除栈顶元素,所以我们pop后需要push回去
    let peekNum = this.popStack.pop();
    this.popStack.push(peekNum);
    return peekNum;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    //两个栈都为空说明队列为空
    return !this.popStack.length && !this.pushStack.length
};