优先级队列封装
// 封装优先级队列 function PriorityQueue() { function QueueElement(element, priority) { this.element = element this.priority = priority } // 封装属性 this.items = [] //1. 实现插入方法 PriorityQueue.prototype.enqueue = function (element, priority) { // 1.创建QueueElement对象 let queueElement = new QueueElement(element, priority) // 2.判断队列是否为空 console.log(this.items) if (this.items.length == 0) { this.items.push(queueElement) } else { let added = false for (let i = 0; i < this.items.length; i++) { if (queueElement.priority < this.items[i].priority) { this.items.splice(i, 0, queueElement) console.log(this.items) added = true break } } if (!added) { this.items.push(queueElement) } } } //2. 从队列中删除前元素 PriorityQueue.prototype.dequeue = ((element, priority) => { return this.items.shift() }) //3. //3.查看前端的元素 PriorityQueue.prototype.front = () => { return this.items[0]; } //4.查看队列是否为空 PriorityQueue.prototype.isEmpty = () => { return this.items.length == 0; } //5.查看队列中的元素个数 PriorityQueue.prototype.size = () => { return this.items.length; } //6.toString方法 PriorityQueue.prototype.toString = () => { let getString = ""; for (let i = 0; i < this.items.length; i++) { getString += this.items[i].element + " "; } return getString; } } // 测试代码 let pq = new PriorityQueue() pq.enqueue("a", 1) pq.enqueue("b", 3) pq.enqueue("c", 2) console.log(pq.items)