优先级队列特点
- 每个元素不再只是一个数据,而且包含数据的优先级
- 在添加方式中,根据优先级放入正确的位置
封装优先级队列
function PriorityQueue() {
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
this.items = [];
PriorityQueue.prototype.enqueue = function (element, priority) {
var queueElement = new QueueElement(element, priority);
if (this.items.length == 0) {
this.items.push(queueElement);
} else {
var added = false;
for (var i = 0; i < this.items.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement);
added = true;
break;
}
}
if (!added) {
this.items.push(queueElement);
}
}
}
PriorityQueue.prototype.dequeue = function (element) {
return this.items.shift();
}
PriorityQueue.prototype.front = function (element) {
return this.items[0];
}
PriorityQueue.prototype.isEmpty = function () {
return this.items.length === 0;
}
PriorityQueue.prototype.size = function () {
return this.items.length;
}
PriorityQueue.prototype.toString = function () {
let resultString = '';
for (let i = 0; i < this.items.length; i++) {
resultString += this.items[i] += " ";
}
return resultString;
}
}
测试
var pq = new PriorityQueue();
pq.enqueue('a', 111);
pq.enqueue('b', 22);
pq.enqueue('c', 333);
pq.enqueue('d', 44);
console.log(pq);