化栈为队

215 阅读1分钟

明确思路

队列的特性是 FIFOFIFO(先入先出),而栈的特性是 FILOFILO(先入后出)。

明白了特性之后。我们就需要两个栈来模拟队列操作,一个为出队栈,一个为入队栈

当出队栈有内容时,出队栈的栈顶即为第一个出队的元素

当出队栈没有内容时,我们就要查询入队栈,将入队栈序列翻转后到出队栈,然后弹出栈顶即可

// 定义两个栈
/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
   this.A = []
   this.B = []
};

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

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  while(this.A.length) this.B.push(this.A.pop())
  const ans = this.B.pop()
  while(this.B.length) this.A.push(this.B.pop())
  return ans
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.A[0]
};

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