The queue follows the FIFO (first first out) principle.
Normal queue
function Queue () { var items=[]; Add one or more elements this.enqueue=function (element) {Items.push (element) to the tail of the queue ; } Remove Queue last this.dequeue=function () { return items.shift (); } Returns the queue first this.front=function () { return items[0]; } Whether the queue is empty this.isempty=function () { return items.length==0; } Returns the queue Length this.size=function () { return items.length; } Print this.print=function () { console.log (items.tostring ()); } }
Priority queue
function Priorityqueue () {var items=[]; function Queueelement (element,priority) {this.element=element; this.priority=priority; The higher the priority value, the lower the precedence this.enqueue=function (element,priority) {var queueelement=new queueeleme NT (element,priority); if (This.isempty ()) {Items.push (queueelement); }else{var added=false; for (var i = 0; i < items.length; i++) {if (queueelement.priority<items[i].priority) {It Ems.splice (i,0,queueelement); Added=true; Break }} if (!added) {Items.push (queueelement); }}}//Remove queue last This.dequeue=function () {return items.shift (); }//Return queue First this.front=function () {return items[0]; }//Whether the queue is empty this.isempty=function () {returnitems.length==0; }//Return queue Length This.size=function () {return items.length; }//Print this.print=function () {Console.log (json.stringify (items)); }}
Demo Loop queue with drum Pass
function Hotpotato (namelist,num) { var queue=new queue (), eliminated= ""; for (var i = 0; i < namelist.length; i++) { queue.enqueue (namelist[i]); } while (Queue.size () >1) {for (var i = 0; i < num; i++) { queue.enqueue (Queue.dequeue ()); } Eliminated=queue.dequeue (); Console.log (eliminated+ "eliminated"); } return Queue.dequeue (); }
Queues in JavaScript