A, queue
A queue is a special kind of linear table, special in that it only allows deletion at the front of the table and insertion at the rear. Like a stack, a queue is a linear table with limited operation. The end that inserts is called the end of the queue, and the end that deletes is called the head of the queue.
Key points: First in first out, last in last out
1.1. Queue implementation
This can be done based on arrays or linked lists
It is easy to implement a queue based on an array as long as you know the nature of the queue
Code demo
class Queue { constructor() { this.items = [] } // 1. Add element enQueue(element) {this.items. Push (element)} // 2. DeQueue () {return this.items. Shift ()} // 3 Front () {return this.items[0]} // 4 IsEmpty () {return this.items. Length === 0} // 5. Size () {return this.items. Length} // 6.toString toString() {return this.items. Join (',')}} let s = new Queue() s.enQueue(1) s.enQueue(2) s.enQueue(3) console.log(s) console.log(s.deQueue()) console.log(s.front()) Console.log (s.isempty ()) console.log(s.size()) console.log(s.tostring ()) // Class PassGame extends Queue { Set (name) {super.enqueue (name)} take(num) {while (super.size() > 1) {for (let I = 0; i < num - 1; I++) {super.enqueue (super.dequeue ())} return super.front()}} let a = new PassGame() a.set('xw') a.set('xh') a.set('xz') a.set('xx') a.set('xe') a.set('xl') console.log(a.take(4))Copy the code
Priority queues
Priority queues are mainly concerned with the following issues: each element is no longer just a data, but also contains the priority of the data;
In the process of adding data, put it in the correct position according to the priority;
2.1 Implementation of priority queue
class PriorityQueue { constructor() { this.items = [] } // 1. Let isAdd = false for (let I = 0, len = this.items. Length; i < len; I ++) {if (priority < this.items[I].priority) {// Insert this.items. Splice (I, 0, {name: name, priority: priority }) isAdd = true break } } if (! isAdd) { this.items.push({ name: name, priority: priority }) } } // 2. DeQueue () {return this.items. Shift ()} // 3 Front () {return this.items[0]} // 4 IsEmpty () {return this.items. Length === 0} // 5. Size () {return this.items. Length} // 6.toString toString() {return this.items. Join (',')}} let s = new PriorityQueue() s.enQueue('xh', 0) s.enQueue('xx', 10) s.enQueue('x2', 120) s.enQueue('xw', 21) s.enQueue('xe', 82) console.log(s.tems) done!Copy the code