JavaScript data structure--queue

Source: Internet
Author: User

A queue is a FIFO data knot. Queues can only insert elements at the end of a queue, deleting elements in the first team, which is not the same as the stack. It is used to store sequentially arranged data. Queues, like our daily queues, are the first to go through the business, and the newcomers can only queue up behind them. The data structure of the queue is used in many places in programming.

To define the operation of a queue

 

Two operations were shown on the queue, queued and out of team. The team operation is to remove the elements of the opponent, the queue operation is to add elements at the end of the team. In addition, we also need to be able to get the elements of the first and the end of the team, or the elements of the team, but also need to know the length of the queue, there is a way to clear the queue, thus, we define the method of the queue.

    • Enqueue () joined the queue
    • Dequeue () the team
    • Front () Back to Team head
    • Back () Return to the end of the team
    • ToString () returns all elements in all queues
    • Length () returns the width of the queue
    • Clear () Empty queue

Implementation of the queue

The array in JavaScript has the disadvantage of having an array of other programming languages, directly using the array's push () method to add elements to the end of the array, and using the Shift () method to delete the first element of the array. Using arrays to implement queues is logical.

Prepare to begin implementing the queue class for the column, starting with the constructor function;

function Queue () {    this. DataStore = [];      this. enqueue = enqueue;     this. dequeue = dequeue;     this. Front = Front;     this. Back = back ;     this. tostring = tostring;     this. length = length;}

The next step is to implement each method of the column.

The Enqueue () method adds an element to the end of the queue, and the Dequeue () method deletes the elements of the first team:

function Enqueue (Element) {    this. Datastore.push (element);    put the new element at the end of the team }function  dequeue ()    {returnthis . Datastore.shift ();     Delete the first element of the team and return this element }

The front () and back () methods are the elements that return the queue's first and the end of the fleet:

function Front () {    returnthis. datastore[0];  // return to Team first element }function back () {    returnthis. datastore[. DATASTORE.LENGTH-1];  // Return to the end of the queue element }

The ToString () method displays all the elements in the queue:

function toString () {    var retstr = ';     this. Datastore.foreach (val + = {   //  traversal queue, all elements in the queue are spelled in a string return        Retstr + = val + ' \ n ' ;    });     return retstr;}

The length () method returns the queue length, and the Clear () method empties the queue:

function Length () {    returnthis. datastore.length;} function Clear () {    this. datastore.length = 0;  // emptying the queue by placing the queue in the long position }

In this case, the data structure of the queue has been implemented with JavaScript. Next Test.

Test of the queue

Test code:

New Queue (); Q.enqueue (' Java '); Q.enqueue (' php ');q.enqueue (' python '); Console.log ( ' all elements in the queue: '); Console.log (q.tostring ()); Q.dequeue () Console.log (' all elements after the team: '); Console.log ( Q.tostring ()); Console.log (' team first element: ' + Q.front ()); Console.log (' tail element: ' + q.back ()); Console.log ( ' Queue Length: ' + q.length () '; Q.clear (); Console.log (' length after emptying queue: ' + q.length ());

Output Result:

The output structure is in line with expectations.

Priority queue

In general, elements that are removed from the queue must be the first to be queued. However, there are special cases that do not follow the first-in-one-out conventions. For example, in the emergency room, the doctor will prioritize the service based on the severity of the patient's condition. In such a queue, the elements removed from the queue may not be the first to be queued. In this case, it is necessary to use a data structure called the priority queue to simulate.

Next, we use the emergency room queue as an example to achieve the following priority queues.

In the emergency room waiting room, the triage nurse evaluates the severity of the patient's condition, then gives a priority code, a high-priority patient to the lower priority patient, and the same priority patient to the first-come-first-served order.

First define the objects that store the queue elements, and then build our priority queue system:

function Patient (name, code) {    this. Name = name;      this. Code = code;    // priority code, Integer, Patient priority }

Now you need to redefine the dequeue () method so that it removes the element with the highest priority in the queue. The element with the lowest value of the priority code is the highest priority. The new Dequeue () method iterates through the underlying storage array of the queue, finds the element with the lowest priority, and then deletes the element. The new Dequeque () method definition is as follows:

 function   Dequeue () {let-priority  =    Span style= "COLOR: #0000ff" >this . Datastore[0].code;    Let pos  = 0;  //  Find the highest-priority element using a simple sequential lookup method  this . Datastore.foreach ((P, i) => { if  (p.code < priority) {Priority  = P.code;        POS  = I;    }    });  //  Returns the element removed from the queue  return  this . Datastore.splice (POS, 1  

Finally, the ToString () method is re-implemented to display the patient object.

function toString () {    var retstr = "";     this. Datastore.foreach (p = {        = ' ${p.name} priority: ${p.code}\n ';    });     return retstr;}

In this way, the simulated emergency priority queue has been completed and we have tested it.

varp =NewPatient ("Xiao Yi", 5); const ED=NewQueue (); Ed.enqueue (p);p=NewPatient ("Little Two", 4); Ed.enqueue (p);p=NewPatient ("Small Three", 6); Ed.enqueue (p);p=NewPatient ("Little Four", 1); Ed.enqueue (p);p=NewPatient ("Little Five", 1); Console.log (' People in line: '); Console.log (ed.tostring ());//First roundEd.enqueue (p);varseen =ed.dequeue (); Console.log (' Patients undergoing admissions: ' + seen[0].name); Console.log (' Waiting for the person: ') Console.log (ed.tostring ());//Next roundvarseen =ed.dequeue (); Console.log (' Patients undergoing admissions: ' + seen[0].name); Console.log (' Waiting for the person: ') Console.log (ed.tostring ());//Next roundvarseen =ed.dequeue (); Console.log (' Patients undergoing admissions: ' + seen[0].name); Console.log (' Waiting for the person: ') Console.log (ed.tostring ());

Input Result:

As you can see, the person to be treated is accepted by priority, one from the queue.

JavaScript data structure--queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.