JavaScript PriorityQueue

function PriorityQueue() {
var items = [];
function QueueElement(element, priority) {
this.element = element;
this.priotity = priority
}
this.enqueue = function(element, priority) {
var queueElement = new QueueElement(element, priority);
if (this.isEmpty()) {
items.push(queueElement)
} else {
var added = false;
for (var 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.print = function() {
console.log(items.toString())
}
this.isEmpty = function() {
return items.length == 0;
}
}
var priorityQueue = new PriorityQueue();
priorityQueue.enqueue('jack', 1);
priorityQueue.enqueue('shidengyun', 2);
priorityQueue.print();
posted @ 2016-01-12 22:23  shidengyun  阅读(1152)  评论(0编辑  收藏  举报