JavaScript data structures and algorithms----queues

Source: Internet
Author: User

Objective

The queue and stack are similar, but with different principles. A queue is an ordered set of items that follow the FIFO principle, and the queue adds new elements at the end, removing elements from the top. The newly added element must be queued at the end of the queue. You can imagine the cafeteria lining up to buy rice.

First, create a queue

1. Create a data structure to hold the contents of the queue, select the array here
2, the method of declaring some stacks
Enqueue (Element (s)): Add one or more elements to the end of the queue
Dequeue (): Removes the first element of the queue (which is the queue at the top) and returns the removed element.
Front (): Returns the first element of the queue (first added), only returns, without modification.
IsEmpty (): Returns True if there are no elements in the queue, false.
Clear (): Clears the elements inside the queue.
Size (): Returns the number of queues.

function Queue () {        var items = [];    this.enqueue= function (Element) {        Items.push (element);    }    This.dequeue = function () {        return items.shift ();    }    This.front = function () {        return items[0];    }    This.isempty = function () {        return items.length = = 0;    }    This.clear = function () {        items = [];    }    This.size = function () {        return items.length;    }    This.print = function () {        console.log (items.tostring ());}    } var queue = new Queue (), Console.log (Queue.isempty ()), Queue.enqueue (' leaf '), Queue.enqueue (' Jack ') Console.log ( Queue.size ()); Console.log (Queue.dequeue ()); Console.log (Queue.isempty ()); Console.log (Queue.size ());

  

Second, circular queue--drum pass the flower game

var namelist = [' leaf ', ' Jack ', ' Jef ', ' Rose ', ' Red ', ' Mandy ', ' Hardy ', ' Mark '];function cyclicgame (namelist) {        var qu Eue = new Queue (),        len = namelist.length;    for (var i=0; i<len; i++) {        queue.enqueue (namelist[i]);    }    var weedoutname = ';    while (Queue.size () >1) {for        (var i=0; I<math.floor (Math.random () *len); i++) {            Queue.enqueue ( Queue.dequeue ());//Remove the first one by adding the following        }        weedoutname = Queue.dequeue ();        Console.log (weedoutname + ' + ' + (Len-queue.size ()) + ' round was eliminated! ');    }    Return Console.log (Queue.dequeue () + ' is the last victor! ');//The last element, Victor}cyclicgame (NameList);

  

Third, event queue management

JS execution Environment is single-threaded, can only complete a task at a time, the scheduling of its tasks is queued, which is registered in the hospital, the front of the person did not fix, you can only stand in the back line waiting. Add a delay to the event queue so that the problem can be mitigated, and the following code simulates the scenario.

var queue = {//Save queue Information items: [],//Add to Queue Enqueue:function (executequeue) {//Add to queue, if not function or number not processed        if (!/function|number/.test (typeof Executequeue)) {return;        } Queue.items.push (Executequeue);    Return a reference to itself return Queue;                },//execute queue executequeue:function () {//delete the first element of the queue and return it var dequeue = Queue.items.shift ();        If the queue is empty, return directly if (!dequeue) {return;            }//If it is a function, execute directly, then proceed to execute Executequeue if (typeof dequeue = = = "function") {dequeue ();            Queue.executequeue ();        Return            }//If it is a number, the number as the delay time, delay Executequeue setTimeout (function () {queue.executequeue ();        Console.log (dequeue);    }, Dequeue); }};//Test queue//Add an event. Enqueue (function () {console.log (' 1th ' after 3 seconds);}).  Enqueue. Enqueue (function () {console.log (' 2nd ' after 3 seconds);  }). Enqueue. Enqueue (function () {console.log (' execute 3rd ' after 3 seconds);})//execute event. Executequeue (); 

  

JavaScript data structures and algorithms----queues

Related Article

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.