<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>优先级队列</title>
</head>
<body>
<script>
//封装优先级队列
function priorityQueue(){
function QueueElement(element,priority){
this.element = element
this.priority = priority
}
//1属性
this.items = []
priorityQueue.prototype.enQueue = function (element, priority) {
//创建对象
var qElement = new QueueElement(element,priority)
//判断队列是否为空
if(this.items.length == 0){
this.items.push(qElement)
}else {
var added = false;
for(var i = 0; i < this.items.length;i++){
if(qElement.priority < this.items[i].priority){
//插入到当前位置
this.items.splice(i,0,qElement)
added = true;
break;
}
}
if(!added){
this.items.push(qElement)
}
}
}
//2删除队列首元素
priorityQueue.prototype.deQueue = function () {
return this.items.shift()
}
//3查看队列前端元素
priorityQueue.prototype.front = function () {
return this.items[0]
}
//4查看队列是否为空
priorityQueue.prototype.isEmpty = function () {
return this.items.length == 0
}
//5查看队列元素个数
priorityQueue.prototype.size = function () {
return this.items.length
}
//6toString方法
priorityQueue.prototype.toString = function () {
var resultString = ''
for(var i = 0; i < this.items.length; i++){
resultString += this.items[i].priority + '-'+this.items[i].element + ' '
}
return resultString;
}
}
//测试代码
var pq = new priorityQueue();
pq.enQueue('abc',11);
pq.enQueue('a',22)
pq.enQueue('b',10)
alert(pq)
</script>
</body>
</html>