1. A queue is a group of ordered items following the first in first out (FIFO) principle. Elements are added at the end of the queue and removed from the top. The newly added elements must be at the end of the queue. Common examples in life, such as queuing.
2. Create a queue class
class Queue{ constructor(){ this.count = 0;//Number of queue records this.lowestCount = 0;//Records the position of the current queue head this.items = [];//Used to store elements. } }
3. Add elements
enqueue(element){ this.items[this.count] = element; this.count++; }
4. Delete element (only delete queue header)
dequeue(){ if(this.isEmpty()){ return 'queue is null'; } let resulte = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return resulte; }
5. View the queue header elements
peek(){ return this.items[this.lowestCount]; }
6. Judge whether the queue is empty
isEmpty(){ return this.count - this.lowestCount === 0; }
7. Clear the elements of the queue
clear(){ this.count = 0; this.lowestCount = 0; this.items = []; }
8. Check the length of the queue
size(){ return this.count - this.lowestCount; }
9. View all contents of the queue
toString(){ if(this.isEmpty())return "queue is null"; let objString = this.items[this.lowestCount]; for(let i = this.lowestCount+1; i < this.count;i++){ objString = `${objString},${this.items[i]}`; } return objString; }
10. Complete code
class Queue{ constructor(){ this.count = 0;//Number of queue records this.lowestCount = 0;//Records the position of the top of the current queue this.items = [];//Used to store elements. } enqueue(element){ this.items[this.count] = element; this.count++; } dequeue(){ if(this.isEmpty()){ return 'queue is null'; } let resulte = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return resulte; } peek(){ return this.items[this.lowestCount]; } isEmpty(){ return this.count - this.lowestCount === 0; } size(){ return this.count - this.lowestCount; } clear(){ this.count = 0; this.lowestCount = 0; this.items = []; } toString(){ if(this.isEmpty())return "queue is null"; let objString = this.items[this.lowestCount]; for(let i = this.lowestCount+1; i < this.count;i++){ objString = `${objString},${this.items[i]}`; } return objString; } }
11. Operation results