JavaScript realizes the queue structure process

JavaScript realizes the queue structure process

1. Understanding Queues

The previous blog has talked about the restricted data structure - the stack. Now, let’s take a look at the Queue .

  • It is a restricted linear list, first in first out ( FIFO ), that is, first in first out.
  • It is limited in that it only allows delete operations on the front of the table.
  • Insertion operations are performed at the rear of the table.

Its structure diagram can be expressed as:

Something similar to queues in life: for example , when we queue up to buy something, first come first served.

2. Encapsulation Queue

The queue structure is also implemented in an array format. First, create a class.

 function Queue(){
            
        }

Add properties and methods inside it, and add the array to the class through the property methods. Then use the prototype method to add commonly used operations.

Common operations on queues are:

  • enqueue (element): Add one (or more) new items to the end of the queue
  • dequeue() : Removes the first item in the queue and returns the removed element.
  • front() : Returns the first element in the queue - the first element to be added and the first element to be removed
  • isEmpty() : Returns true if the queue does not contain any elements, otherwise returns false
  • size() : Returns the number of elements in the queue
  • toString() : Convert the contents of the queue into a string

Now let’s implement it:

function Queue(){
     this.items = [];
     //Add one (or more) new items to the end of the queue enqueue()
     Queue.prototype.enqueue = function(element){
         this.items.push(element);
     }
     //Remove the first item in the queue (i.e. the front item in the queue) dequeue()
     Queue.prototype.dequeue = function(){
          return this.items.shift();
      }
     //Return the first element in the queue front()
     Queue.prototype.front = function() {
          return this.items[0];
      }
     // Check if the stack is empty isEmpty()
     Queue.prototype.isEmpty = function(){
         return this.items.length == 0;
     }
     //Return the number of elements contained in the queue size()
     Queue.prototype.size = function(){
         return this.items.length;
     }
     //Convert the contents of the queue into a string form toString()
     Queue.prototype.toString = function(){
         var str = '';
         for(var i =0;i<this.items.length;i++){
             str += this.items[i] + ' ';
         }
         return str;
     }
 }   

The above is the encapsulation of the queue, now verify it:

 var queue = new Queue();
 queue.enqueue(10);
 queue.enqueue(20);
 queue.enqueue(30);
 queue.enqueue(40);
 queue.enqueue(50);
 console.log(queue);
 console.log('The first item removed is: ' + queue.dequeue());
 console.log('The first element in the queue is: ' + queue.front());
 console.log('Is the stack empty: '+queue.isEmpty());
 console.log('The contents of the stack structure are:');
 console.log(queue.toString());

The output is:

Build successful.

Let’s take a look at a case of passing the parcel while beating the drum!

3. The Case of Passing the Flower by Beating the Drum

Original game rules:

  • Play a game in the class. All students stand in a circle and pass a bouquet of flowers from one student to the next student.
  • At this time, a man is beating a drum. When the drum stops, whoever holds the flower will be punished.

Modify the game rules:

  • A few friends play a game together. They sit in a circle and start counting. The person who counts to a certain number is automatically eliminated.
  • The last person left wins. Which position does the last person left from win?

Encapsulate a queue-based function:

  • Parameters: names of all participants, numbers based on
  • Result: The name of the person who is left at the end

The code is as follows:

 // Encapsulate queue function Queue(){
     this.items = [];
     //Add elements at the end Queue.prototype.enqueue = function(element){
         this.items.push(element);
     }
     //Remove the first element Queue.prototype.dequeue = function(){
         return this.items.shift();
     }
     //Return the first element Queue.prototype.front = function(){
         return this.items[0];
     }
     //Return the number of elements contained in the queue Queue.prototype.size = function(){
         return this.items.length;
     }
 }
 
 function passGame(nameList,num){
     // Create a queue var queue = new Queue();
     //Add all people to the queue for(var i = 0;i<nameList.length;i++){
         queue.enqueue(nameList[i]);
     }
     //Play the game while (queue.size() > 1) {
         //The people before num are added to the end of the queue for(var i =1;i<num;i++){
             queue.enqueue(queue.dequeue());
         }
       //People with num numbers are directly removed from queue.dequeue();
    }
    //Get the winner information var endName = queue.front();
    console.log('The remaining people are:' + endName);
    return nameList.indexOf(endName);
 }
 
 //Test var nameList = ['a','b','c','d','e'];
 var g = passGame(nameList,5);
 console.log('This person's location is: '+g);

The output is:

This is the end of this article about the process of implementing queue structure in JavaScript. For more relevant content about implementing queue structure in JavaScript, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript queue structure Queue implementation process analysis
  • Example analysis of data structure queue animation based on JavaScript
  • Detailed explanation of the queue example in JS algorithms and data structures
  • JavaScript data structure and algorithm queue principle and usage example detailed explanation
  • Data structures and algorithms in JavaScript (Part 2): Queues
  • JavaScript data structure and algorithm stack and queue

<<:  How to do a good refactoring is not only refactoring the code but also refactoring life

>>:  Introduction to basic concepts and technologies used in Web development

Recommend

Detailed tutorial on installing Tomcat9 windows service

1. Preparation 1.1 Download the tomcat compressed...

LINUX Checks whether the port is occupied

I have never been able to figure out whether the ...

Tutorial on installing php5, uninstalling php, and installing php7 on centos

First, install PHP5 very simple yum install php T...

Detailed explanation of nginx request header data reading process

In the previous article, we explained how nginx r...

Introduction to the process of installing MySQL 8.0 in Linux environment

Table of contents Preface 1. Linux changes the yu...

Use and analysis of Mysql Explain command

The mysql explain command is used to show how MyS...

Introduction to Sublime Text 2, a web front-end tool

Sublime Text 2 is a lightweight, simple, efficien...

Implementing WeChat tap animation effect based on CSS3 animation attribute

Seeing the recent popular WeChat tap function, I ...

How to use worm replication in Mysql data table

To put it simply, MySQL worm replication is to co...

Summary of commonly used tags in HTML (must read)

Content Detail Tags: <h1>~<h6>Title T...

Nested display implementation of vue router-view

Table of contents 1. Routing Configuration 2. Vue...