JS data structure and algorithm → queue structure

tags: JS data structure and algorithm

table of Contents

1. What is a queue?

2. Common operations of the queue

3. Encapsulation queue structure

4. The use of queues

5. Application of the queue structure — drum-drum transmission algorithm

6. Application of queue structure-priority queue


1. What is a queue?

Queue (Queue), it is a restricted linear table, first in first out (FIFO First In First Out), the limitation is that it only allows the delete operation in the front of the table (front), and after the table Insert the terminal (rear). FIFO (First In First Out) identifies the elements of the advanced team. It is the first to leave the team. It is similar to the ticket gate of the movie theater. The first arrival will take the ticket first. Inserting a new element into a queue is also called queuing and enqueuing. It puts the new element at the end of the queue and makes it a new tail element; deleting an element from a queue is also called making a team. The element is deleted to make its adjacent element the new leader element. The schematic diagram is as follows:
 

2. Common operations of the queue

method Explanation
enqueue() Add one (or more) new items to the end of the queue
dequeue() Remove the first item in the queue (that is, the first item in the queue) and return the removed element
front() Return the first element in the queue, which will also be the first element removed
isEmpty() True if the queue contains no elements, otherwise false
size() Returns the number of elements in the queue, similar to the length property of the array
toString() Convert the contents of the queue into a string

3. Encapsulation queue structure

Implement the stack structure based on the array, and add some queue methods to the prototype of the encapsulated Queue () class.

function Queue () {// package queue class
    var items = [];
    
         // Method of queue operation
         // 1. Add the element to the queue
    Queue.prototype.enqueue = function(element){
        this.items.push(element);
    }
         // 2. Remove the front-end element from the queue
    Queue.prototype.dequeue = function () {
        return this.items.shift();
    }
         // 3. View the elements at the front of the queue
    Queue.prototype.front = function () {
        return this.items[0];
    }
         // 4. Check if the queue is empty
    Queue.prototype.isEmpty = function () {
        return this.items.length == 0;
    }
         // 5. View the number of elements in the queue
    Queue.prototype.size = function () {
        return this.items.length;
    }
         // 6. View the number of elements in the queue
    Queue.prototype.toString = function(){	
        var resultString = '';
        for(var i in this.items){
            resultString += this.items[i] + '-'
        }
        return resultString;
    }
}

4. The use of queues

Based on the queue just encapsulated, some basic operations of the queue are performed.

// Create queue object
var queue = new Queue();

 // Add elements to the queue
queue.enqueue("abc");
queue.enqueue("bcd");
queue.enqueue("cde");

 // Look at the front element of the queue
alert(queue.front());      //abc

 // Check if the queue is empty and the number of elements
alert(queue.isEmpty());    //false
alert(queue.size());       //3

 // Remove elements from the queue
alert(queue.dequeue());    //abc
alert(queue.dequeue());    //bcd
alert(queue.dequeue());    //cde

5. Application of the queue structure — drum-drum transmission algorithm

Game rules: Several friends form a circle, start counting, the person who counts to a certain number is automatically eliminated, and then continue with the same rule from the next person, the last person will win, please ask the last remaining Where is the original person?

(1) Main principle: Create a queue, put everyone in the queue, and then dequeue each element in the queue through a loop. If this element is not the num-th number, then enqueue it again and repeat the loop until there is one left in the queue When an element is output, it is the person who ultimately wins.

(2) Code implementation

// The function to realize drumming and passing flowers
function passGame(nameList, num) {
         // 1. Create a queue and put all the people in the queue
    var queue = new Queue();

         // 2. Through the for loop, put the people in the nameList in the queue
    for (var i=0; i <nameList.length; i++) {
        queue.enqueue(nameList[i]);
    }

         // 3. Find the last person left
    while (queue.size() > 1) {
                 // Remove the people in the former num-1 from the front of the queue and put them on the back of the queue
        for (var i=0; i <num-1; i++) {
            queue.enqueue(queue.dequeue());
        }

                 // Remove the num person from the queue
        queue.dequeue();
    }

         // 4. Get the remaining one
    alert(queue.size());    //1
    var endName = queue.dequeue();
         alert ("The person who finally stays:" + endName);

         // 4. Get the person's position in the queue
    return nameList.indexOf(endName);
}
 // Validation results 
var names = ['AAA','BBB','CCC','DDD','EEE'];
 var index = passGame (names, 7); // People who count to 8 are eliminated
 alert ("Final position:" + index);

6. Application of queue structure-priority queue

(1) Characteristics of priority queue: An ordinary queue inserts an element, the data will be placed in the back end, and the current data will not be processed until all the previous elements have been processed. However, the priority queue will consider the priority of the data when inserting an element. Before inserting, compare with the priority of other data. After the comparison is completed, you can get the correct position of the element in the queue.

Is it not easy to understand? There are examples of priority queues in life, such as seniors and pregnant women (or women with children) who have higher priority than other passengers when they ride in the car, and first-class and business class passengers Higher than economy class passengers.

(2) Code implementation

// Package priority queue
function PriorityQueue(){
         // Recreate a class inside PriorityQueue, which can be understood as an inner class
    function QueueElement(element,priority){
        this.element = element;
        this.priority = priority;
    }
         // Package properties
    this.items = [];
	
         // 1. Compare the limits of the elements and put them into the corresponding position
    PriorityQueue.prototype.enqueue = function(element,priority){
                 // 1. Create QueueElement object
        var queueElement = new QueueElement(element,priority);
		
                 // 2. Determine whether the queue is empty
        if(this.items.length == 0){
            this.items.push(queueElement)
        }else{
            var added = false;
            for (var i=0;i<this.items.length;i++) {
                if(queueElement.priority < this.items[i].priority){
                    this.items.splice(i,0,queueElement)
                    added = true;
                    break;
                }
            }
            if(!added){
                this.items.push(queueElement)
            }
        }
    }
         // 2. Remove the front-end element from the queue
    PriorityQueue.prototype.dequeue = function () {
        return this.items.shift();
    }
         // 3. View the elements at the front of the queue
    PriorityQueue.prototype.front = function () {
        return this.items[0];
    }
         // 4. Check if the queue is empty
    PriorityQueue.prototype.isEmpty = function () {
        return this.items.length == 0;
    }
         // 5. View the number of elements in the queue
    PriorityQueue.prototype.size = function () {
        return this.items.length;
    }
         // 6. View the elements in the queue
    PriorityQueue.prototype.toString = function(){	
        var resultString = '';
        for(var i in this.items){
            resultString += this.items[i].element + '-' + this.items[i].priority + '-' 
        }
        return resultString;
    }
}

(3) Test code

// Test code
var pq = new PriorityQueue();
pq.enqueue('abc','111');
pq.enqueue('bcd','115');
pq.enqueue('cde','110');
alert(pq);        //cde-110-abc-111-bcd-115-

Intelligent Recommendation

JS [JavaScript] data structure and algorithm of the queue

Many front-end engineers areWithout solid foundation, Little knowledge of data structures and algorithms, or worse still have "I write a page, what algorithm would use" similar mentality. Th...

Data structure and algorithm queue (JS description)

What is a queue Queue is a first-in-first-out orderly structure. The most common thing in our lives is to queue up, and whoever comes first will serve the first. You can often see it in the program, s...

js data structure and algorithm (2) stack and queue

1. Stack 1. Definition The stack is an important linear structure. Stack is aLast in first out(Last in first out, LIFO) linear table, it requires only delete and insert operations at the end of the ta...

3. Queue of js data structure and algorithm

1 Introduction Queue is a first-in-first-out (First-In-First-Out, FIFO) data structure. Queues are used in many places, such as submitting a series of processes executed by the operating system, print...

More Recommendation

Data structure and algorithm JS description stack and queue

Data structure and algorithm JS description stack and queue Reference Data structure and algorithm JS description, [America] Michael McMillan, translated by Wang Qunfeng and Du Huan Write in front The...

Data structure and algorithm (js description) --- queue

Definition of queue Like the stack, the queue is a linear list with limited operations. But unlike the stack, the queue is only allowed to insert at one end of the table and delete at the other end of...

Data structure and algorithm - JS implementation (stack and queue)

JavaScript implementation stacks and queues This implementation is relatively simple, there is no function. Stack queue Stack queue...

Queue structure of js data structure

Queue structure FIFO (First In First Out) Allow to delete at the front (front) and insert at the back (rear) Special: Priority queue Encapsulate a queue structure yourself Interview Question: Beat the...

JS data structure - queue

queue A queue is an ordered set of items that follows a First In First Out (FIFO) queue that adds new elements at the end and removes elements from the top. The newly added elements must be placed at ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top