在简单的进行了对列的学习后,我们开始来学习优先级队列

<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>优先级队列的封装
// 1.封装优先级队列!
function PriorityQueue(){
//在PriorQueue中重新创建了一个类,可以理解为内部类!
function QueueElement(element,priority){
//一个用于保存数据,一个用于保存优先级!
this.elements=element
this.priority=priority
}
// 封装属性
this.items=[]
// 实现插入方法
PriorityQueue.prototype.enqueue= (element,priority)=>{
// 1,创建QueueElement对象
let queueElement=new QueueElement(element,priority)
// 2.判断队列是否为空
// 如果队列为空,则插入的队列为第一个,直接push进入栈即可
// 如果队列不为空,则先判断优先级,再进行push进队列!
if (this.items.length===0){
this.items.push(queueElement)
}else{
//添加added变量,判断这个数是否插入了对列中,如果插入了对列,
// added的值变为false,否则,added的值变为true,同时,退出循环!
let added=false;
for (let i=0;i
if (queueElement.priority
this.items.splice(i,0,queueElement)
added=true
break
}
}
//因为添加过程中,如果循环完,没有added=true的,则就是添加在队列的末尾!
if (!added){
this.items.push(queueElement)
}
}
}
// 2.从队列中删除首要元素
PriorityQueue.prototype.dequeue=()=>{
//这是js中的shift删除方法,用于把数组中第一个元素的值从其中删除,并返回第一个元素的值
return this.items.shift()
}
// 3.查看当前的元素
PriorityQueue.prototype.front=()=>{
return this.items[0]
}
// 4.查看队列是否为空
PriorityQueue.prototype.isEmpty=()=>{
return this.items.length===0
}
// 5.查看队列中元素的个数
PriorityQueue.prototype.size=()=>{
return this.items.length
}
// 6.toSting的方法
PriorityQueue.prototype.toString=()=>{
let resultString=' '
for (let i=0;i
resultString +=this.items[i].elements+'-'+this.items[i].priority+' '
}
return resultString;
}
}
// 测试代码
let pq=new PriorityQueue()
pq.enqueue('tbc',111)
pq.enqueue('cab',200)
pq.enqueue('nbc',50)
pq.enqueue('nbc',60)
alert(pq)
</html>
测试结果:
