数据结构与算法2:用JavaScript 实现 队列 结构
队列 区别于 栈 的 【后进先出】 ,数据结构特点为 【先进先出】。用数组较易实现,本文为区别于栈结构,故封装 优先队列 ,即加入权重指标(权重越高,则优先输出)。
常用方法:
-
enqueue(element, priority) 插入元素 dequeue() 删除顶部队列元素 front() 查看队列顶部元素 isEmpty() 判断是否为空 size() 查看队列个数 toString() 方法
// 封装优先队列 function PriorityQueue(){ // 新建一个队列元素的内部类 function QueueElement(element, priority){ this.element = element; this.priority = priority; } // 封装属性 this.items = []; // 1 实现插入 PriorityQueue.prototype.enqueue = function (element, priority){ // 创建QueueElement对象 var queueElement = new QueueElement(element, priority); // 判断队列是否为空,若为空则直接插入 if(this.items.length === 0 ){ this.items.push(queueElement); } else { let isContinue = true; for (var i = 0 ; i < this.items.length; i++){ // 对比优先级,权重越高优先级越高 if(queueElement.priority > this.items[i].priority){ this.items.splice(i, 0, queueElement); isContinue = false; break } } // 权重最低,则在队尾插入 if(isContinue){ this.items.push(queueElement); } } }; // 2 从队列中删除前端元素 PriorityQueue.prototype.dequeue = function (){ return this.items.shift() } // 3 查看前端元素 PriorityQueue.prototype.front = function (){ return this.items[0] } // 4 查看队列是否为空 PriorityQueue.prototype.isEmpty = function (){ return this.items.length === 0 } // 5 查看队列个数 PriorityQueue.prototype.size = function (){ return this.items.length } // 6 toString方法 PriorityQueue.prototype.toString = function () { let resultString = ; for (let index = 0; index < this.items.length; index++) { resultString += this.items[i] + ; } return resultString } } // 测试用例 var pq = new PriorityQueue(); // enqueue方法 pq.enqueue(abc, 100) pq.enqueue(efg, 50) pq.enqueue(hij, 300) console.log(pq);