1. Preface
Queue is an ordered collection that adheres to the FIFO (fifo,first-in-first-out) principle. The queue adds a new element at the end and removes the element from the top, and the newly added element must be at the bottom of the queue.
2. Function description
- Enqueue (value): Enter the team, add a new element to the end of the queue
- Dequeue (): Team out, remove the first element in the queue, and return the element
- Front (): Gets the first element in a queue
- IsEmpty (): Determines whether the queue is empty. Yes returns True, no return fallse
- Clear (): Empty the elements in the queue
- Size (): Gets the number of elements in the queue
3. Code implementation
First, create a class to represent the queue, and initialize an empty array to hold the elements in the queue
class Queue { constructor () { this. Items = []; };
Next, implement the required functionality in this queue class:
class Queue {constructor () { This. Items = []; } //Into the team, from the tail of the team.Enqueue (value) { This. Items.push (value); } //Out of the team from the head of the team outdequeue () {return This. Items.shift (); } //get the first element in a teamFront () {return This. items[0]; } //determine if the team is emptyIsEmpty () {return This. Items.length = = 0; } //get the number of elements in a teamsize () {return This. Items.length; } }
4. Testing
Here, we can use the queue to simulate the game of ' drumming and passing flowers ':
/** Name: Drum Pass * parameter: Namearr, an array that contains all the names of the people who participated in the game; * Num, the number of drums * back: Final game winner's name*/ functionJGCH (Namearr, num) {varQueue =NewQueue ();//Instantiate a queue for(vari = 0; i < namearr.length; i++) {queue.enqueue (namearr[i]);//joins the name of the person in the incoming array into the queue } varTaotai = ' '; while(Queue.size () > 1) { for(vari = 0; i < num; i++) { //each time you hit a drum, move an item at the beginning of the queue to the end of the teamQueue.enqueue (Queue.dequeue ()); } //The beating of the drums, the man holding the flowers, was eliminated, moved out of the queueTaotai =Queue.dequeue (); Console.log (Taotai+ ' be eliminated!!! ‘); } //The last person left in the queue is the ultimate winner. returnQueue.dequeue (); }varNamearr = [' Guo Jing ', ' Zhang Mowgli ', ' Qiao ', ' Imaginary bamboo ', ' Duan Yu '];console.log (' The ultimate winner is: ' + JGCH (Namearr, 10));
Game results:
Native JS implementation team structure and the use of the queue simulation ' drum pass the flower ' game