/**
* 优先队列:元素的添加和删除是基于元素的优先级的
*
* 两种实现方式:
* (1)设置优先级,然后再正确的位置添加元素;
* (2)入列添加元素,按照元素的优先级移除他们
* @constructor
*/
function PriorityQueue() {
let items = [];
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
this.enqueue = function (element, priority) {
let queueElement = new QueueElement(element, priority);
let added = false;
for (let i = 0; i < items.length; i++) {
if (queueElement.priority < items[i].priority) {
items.splice(i, 0, queueElement);
added = true;
break;
}
}
if (!added) {
items.push(queueElement);
}
};
this.dequeue = function () {
return items.shift();
};
this.front = function () {
return items[0];
};
this.size = function () {
return items.length;
};
this.isEmpty = function () {
return items.length === 0;
};
this.print = function () {
for (let i = 0; i < items.length; i++) {
console.log(`${items[i].element} - ${items[i].priority}`)
}
};
}
数据结构与算法--优先队列
最新推荐文章于 2018-09-30 17:42:36 发布