[路飞]_程序员必刷力扣题: 面试题 03.04. 化栈为队

349 阅读2分钟

面试题 03.04. 化栈为队

实现一个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 操作)。

从大到小反转排序

思路

用栈的方式模拟队列

我们只能用栈的先进先后出的特性,push和pop

如果我们要实现队列的先进先出特性,我们必须要访问到栈的第一个元素,这里我们用两个栈来模拟,

声明两个栈一个进入栈inStack 一个 出栈outStack,

当我们要进入队列push的时候直接添加到inStack中即可,

当我们要出队列pop的时候,需要访问栈底的元素,因此我们要先将栈逐个放入outStack中,这样原来栈底的元素就到了栈顶(我们这里直接将栈底以外的元素放入outStack,然后将inStack的唯一的元素弹出返回即可,然后再将OUtStack中的元素放回inStack)

  • push: 直接用数组的push,将元素放入inStack中
  • pop: 我们需要先对inStack进行反转然后再弹出inStack栈底的元素,最后再反转回来
  • peek: 道理同pop,只是不需要弹出,只要返回值即可
  • empty: 返回inStack的length是否为空
/**
 * 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())
    }
    var res = this.inStack.pop();
    while(this.outStack.length){
        this.inStack.push(this.outStack.pop())
    }
    return res;
};

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

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.inStack.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()
 */