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 () {
return this.items.shift()
}
//查看前端元素
priorityQueue.prototype.front = function () {
return this.items[0]
}
priorityQueue.prototype.isEmpty = function () {
return this.items.length == 0
}
// 5. 查看元素中的个数
priorityQueue.prototype.size = function () {
return this.items.length;
}
// 6. toString
priorityQueue.prototype.toString = function () {
var resultString = '';
for (var i = 0; i < this.items.length; i++) {
resultString += this.items[i].element + "-" + this.items[i].priority + " ";
}
return resultString;
}
};
// 测试代码
var pq = new priorityQueue();
pq.enqueue('abc', 111);
pq.enqueue('bweqw', 222);
pq.enqueue('dede', 444);
pq.enqueue('csaq3ew', 333);
alert(pq.toString());