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

Answer:

It refers to the third method of official problem solving (a queue, press -O (n)O(n), pop -o (1)O(1)).

Elements are added to the end of the queue when pushed, and the elements before them are removed and stored at the end of the queue. The queue is then flipped once, and the dequeue operation becomes the destack operation.

/**
 * Push element x onto stack.
 * @param {number} x
 * @return {void}* /
MyStack.prototype.push = function (x) {
  // The pushed elements are queued directly
  this.q.push(x);

  This.q.length-1; // The last elements of the queue are removed from the queue at the same time, so this.q.length-1.
  // After the operation, the queue is sorted in the order in which the queue is removed from the stack.
  for (let i = 0; i < this.q.length - 1; i++) {
    this.q.push(this.q.shift()); }};/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}* /
MyStack.prototype.pop = function () {
  return this.q.shift();
};

/**
 * Get the top element.
 * @return {number}* /
MyStack.prototype.top = function () {
  return this.q[0];
};

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