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

An Uncommon Error and Solution for SQL Server Full Backup

1. Error details Once when manually performing a ...

Detailed explanation of angular content projection

Table of contents Single content projection Multi...

How to use MySQL binlog to restore accidentally deleted databases

Table of contents 1 View the current database con...

How to make CSS child elements highly consistent with parent elements

Absolute positioning method: (1) Set the parent e...

Basic application methods of javascript embedded and external links

Table of contents Basic application of javascript...

Linux installation apache server configuration process

Prepare the bags Install Check if Apache is alrea...

Some summary of MySQL's fuzzy query like

1. Common usage: (1) Use with % % represents a wi...

How to create a virtual environment using virtualenv under Windows (two ways)

Operating system: windowns10_x64 Python version: ...

Vue achieves the top effect through v-show

html <div class="totop" v-show="...

Detailed graphic tutorial on installing and uninstalling Tomcat8 on Linux

[ Linux installation of Tomcat8 ] Uninstall Tomca...

How to use Docker to limit container resources

Problem Peeping In the server, assuming that the ...

How to check if the firewall is turned off in Linux

1. Service method Check the firewall status: [roo...

MySQL Index Optimization Explained

In daily work, we sometimes run slow queries to r...