优先级队列封装
// 封装优先级队列 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)
相关推荐
wikiwater 2020-10-27
IdeaElements 2020-08-19
Sophiego 2020-08-16
Kakoola 2020-08-01
Kakoola 2020-07-29
ELEMENTS爱乐冬雨 2020-07-18
ELEMENTS爱乐小超 2020-07-04
ELEMENTS爱乐小超 2020-07-04
Kakoola 2020-06-28
Feastaw 2020-06-18
Wmeng0 2020-06-14
ELEMENTS爱乐冬雨 2020-06-14
云之高水之远 2020-06-14
哈喽elements 2020-06-14
Feastaw 2020-06-11