Skip to content

Latest commit

 

History

History
73 lines (65 loc) · 1.67 KB

用栈实现队列.md

File metadata and controls

73 lines (65 loc) · 1.67 KB
/**
 * 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 () {
  // 出队操作 如果出队的栈中没有元素 则从入队的栈中转移元素
  if (!this.outStack.length) {
    this.transfer();
  }
  // 弹出出栈的最新的元素 即出队操作
  return this.outStack.pop();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
  // 返回队头元素
  if (!this.outStack.length) {
    this.transfer();
  }

  return this.outStack[this.outStack.length - 1];
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
  // 判断队列是否为空 则校验出队和入队的栈中是否长度为 0
  return this.outStack.length === 0 && this.inStack.length === 0;
};

// 执行从 inStack 转移元素到 outStack
MyQueue.prototype.transfer = function () {
  while (this.inStack.length) {
    this.outStack.push(this.inStack.pop());
  }
};

/**
 * 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()
 */