1. Title Description

For a more detailed description of the topic, seeLeetcode topic link

Second, the analysis

  • Stack characteristics: last in first out, at the top of the stack to add and delete operations
  • Queue features: first in first out, delete at the first queue, add at the last queue
  • JavaScript does not have a stack as a native data structure, and uses arrays to simulate stacks
  • Use two stacks to simulate queues
  • The push stack is used to simulate queuing
  • The POP stack is used to simulate queuing
  • When the POP stack is empty, all elements in the push stack need to be removed from the stack and merged into the pop stack, reversing the process to achieve fifO

Three, code,

Git code address

Var MyQueue = function() {this.pushstack = [] this.popstack = []};  /** * Push element x to the back of queue. * @param {number} x * @return {void} */ MyQueue.prototype.push = function(x) {// Push this.pushstack.push (x)}; /** * Removes the element from in front of queue and returns that element. * @return {number} */ MyQueue.prototype.pop = Function () {// If the pop stack is empty, we need to push all elements out of the pop stack, and reverse the process if(! This.pushstack.length) {this.pushstack.length) {this.popstack.push (this.pushstack.pop ())}} Pop return this.popstack.pop ()}; /** * Get the front element. * @return {number} */ myqueue.prototype. peek = function() { Returning the head of the queue is equivalent to returning the top of the pop stack if(! this.popStack.length) { while(this.pushStack.length) { this.popStack.push(this.pushStack.pop()) } } const peek = this.popStack.pop() this.popStack.push(peek) return peek }; /** * Returns whether the queue is empty. * @return {Boolean} */ myqueue.prototype. empty = function() Return! If pop stacks are not empty, this queue is not empty. this.pushStack.length && ! this.popStack.length }; /** * 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() * /Copy the code