web123456

JavaScript data structure: queue

  • function Queue() {
  • //Team Head
  • this.head = null
  • //The end of the team
  • this.tail = null
  • //The length of the team
  • this.length = 0
  • //node
  • function Node(value) {
  • this.value = value
  • this.next = null
  • }
  • //Enter the team
  • Queue.prototype.push = function (val) {
  • const node = new Node(val)
  • if (this.length === 0) {
  • //If the queue length is 0, the head and tail of the team point to the new insertion node
  • this.head = node
  • this.tail = node
  • } else {
  • //If the queue length is greater than 0, the next at the end of the queue points to the new insertion node
  • this.tail.next = node
  • //The tail of the team moves one backwards and points to the newly inserted node
  • this.tail = this.tail.next
  • //The next at the end of the moving team points to the head of the team
  • this.tail.next = this.head
  • }
  • //Insert is completed, the queue length is 1
  • this.length++
  • }
  • //Get out of the team
  • Queue.prototype.remove = function () {
  • //If the queue length is 0, return null
  • if (this.length === 0) return null
  • else {
  • //The value of the team leader to be removed
  • const value = this.head.value
  • if (this.length === 1) {
  • //When the length of the queue is 1, the queue will be empty after dequeuing the queue
  • //At this time, the head and tail of the team are null
  • this.head = null
  • this.tail = null
  • } else if (this.length === 2) {
  • //When the queue length is 2, after leaving the queue, the queue length is 1
  • //At this time, the head and tail of the team point to the tail of the team at the same time, and the next of the tail of the team points to null
  • this.tail.next = null
  • this.head = this.tail
  • } else {
  • //Move the team leader one by one back
  • this.head = this.head.next
  • //The next at the end of the team points to the new team leader
  • this.tail.next = this.head
  • }
  • // Complete dequeue, reduce the queue length by one
  • this.length--
  • return value
  • }
  • }
  • //Return the value of the header element
  • Queue.prototype.front = function () {
  • //If the queue length is 0, return null
  • if (this.length === 0) return null
  • //Reversely return to the value of the head of the team
  • return this.head.value
  • }
  • //Judge whether the queue is empty
  • Queue.prototype.isEmpty = function () {
  • // Directly determine whether the length of the queue is equal to 1
  • return this.length === 0
  • }
  • //Get the queue size
  • Queue.prototype.size = function () {
  • //Return directly to the length of the queue
  • return this.length
  • }
  • }