元素的添加是基于优先级的。
function PriorityQueue() {
var items = [];
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
this.enqueue = function(element, priority) {
const queueElement = new QueueElement(element, priority);
if(this.isEmpty()) {
items.push(queueElement);
}else {
var isAdded = false;
for(let i=0; i< this.size(); i++) {
const ele = items[i];
if(ele.priority > priority) {
items.splice(i, 0, queueElement);
isAdded = true;
break;
}
}
if(!isAdded) {
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() {
console.log(items.toString);
}
}
const priorityQueue = new PriorityQueue();
priorityQueue.enqueue('a', 2);
priorityQueue.enqueue('b', 3);
priorityQueue.enqueue('c', 1);
priorityQueue.enqueue('d', 1);
console.log(priorityQueue.front()); // QueueElement { element: 'c', priority: 1 }
priorityQueue.dequeue();
console.log(priorityQueue.front()); // QueueElement { element: 'd', priority: 1 }