[路飞]_leetcode-面试题03.04-化栈为队

[题目地址]

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

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false
复制代码

说明:

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

本题很简单,就是让我们用两个栈模拟完成一个队列

队列的性质是 先进先出(FIFO)

栈的性质是 先进后出(FILO)

本题只需要维护两个栈,一个栈用来做入队栈,一个用来做出队栈

push 操作的时候,将元素压入入队栈,peakpop 操作的时候从出队栈获取元素

当出队栈没有元素的时候,从入队栈依次弹出每个元素压入出队栈,因为栈是先进后出的,此时入队栈的栈顶元素为最后入栈的,如此顺序压入出队栈后,出队栈栈顶即为最早入栈的元素

动画演示如下:

leetcode-面试题03.04-化栈为队.gif

代码如下:

var MyQueue = function() {
  // 入队栈
  this.stackin = []
  // 出队栈
  this.stackout = []
};

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  // 出队栈为空时,从入队栈导入所有元素
  if(!this.stackout.length)
    while(this.stackin.length){
      this.stackout.push(this.stackin.pop())
    }
  return this.stackout.pop();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
  // 出队栈为空时,从入队栈导入所有元素
  if(!this.stackout.length)
    while(this.stackin.length){
      this.stackout.push(this.stackin.pop())
    }
  return this.stackout[this.stackout.length-1]
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  return this.stackin.length===0&&this.stackout.length===0
};
复制代码

至此我们就完成了 leetcode-面试题03.04-化栈为队

如有任何问题或建议,欢迎留言讨论!

猜你喜欢

转载自juejin.im/post/7036940900257234958