Original link: leetcode-cn.com/problems/im…

Answer:

  1. All elements are present in s1, and the first enqueued element is cached as the head of the queue.
  2. When leaving a team, all elements except the head of the team are cached to S2, and then the only remaining element of S1 is pop.
  3. After pop is complete, s2 cached elements are returned to S1 in turn.
/** * Initialize your data structure here. */
var MyQueue = function () {
  this.s1 = []; // Store the queue
  this.s2 = []; // Temporarily store data when pop
  this.top = null; // Store queue head
};

/**
 * Push element x to the back of queue.
 * @param {number} x
 * @return {void}* /
MyQueue.prototype.push = function (x) {
  // Store the first joining element as the head of the queue
  if (!this.s1.length) {
    this.top = x;
  }
  // All elements are pushed normally
  this.s1.push(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}* /
MyQueue.prototype.pop = function () {
  // if s1 is 1, the stack is cleared, so the first queue is cleared, but the use case is not validated here
  if (this.s1.length <= 1) {
    this.top = null;
  }

  // move all s1 elements to s2
  while (this.s1.length > 1) {
    this.top = this.s1.pop();
    this.s2.push(this.top);
  }

  // Remove the first queue element from the stack and cache it
  const pop = this.s1.pop();

  // Return all s2 elements to s1, keeping the order of the elements
  while (this.s2.length) {
    this.s1.push(this.s2.pop());
  }

  return pop;
};

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

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