The characteristics of
When a normal queue inserts an element, the data is put to the back end and not processed until all previous elements have been processed
However, the priority queue considers the priority of the data when inserting an element and compares it with other data priorities. After the comparison, the correct position of the element in the queue can be obtained
Scenes from life
For example, boarding, first and business class are given higher priority than economy class
And the emergency department, where patients with serious medical needs are given high priority
<script> class QueueElement { constructor(element, priority) { this.element = element this.priority = priority } } class PriorityQueue { constructor() { this.items = [] } Enqueue (element, priority) {// According to the element passed, Let QueueElement = new QueueElement(element, If (this.items. Length === 0) {// If (this.items. Length === 0) { This.items. Push (queueElement)} else {// Define a variable to record whether a new element was successfully added var Added = false for (let I = 0; i < this.items.length; I++) {// let the newly inserted element compare priority, the smaller the priority value, If (queueelement.priority < this.items[I].priority) {// Insert element this.items. Splice (I, 0, QueueElement) added = true break}} if (! QueueElement) added = true break} added) { this.items.push(queueElement) } } } // 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 method toString() {let result = "; for (let item of this.items) { result += item.element + '-' + item.priority + ' '; } return result; } } var p1 = new PriorityQueue() p1.enqueue('abc', 90) p1.enqueue('eee', 190) p1.enqueue('ty', 50) p1.enqueue('ca', 100) console.log(p1.toString()); </script>Copy the code