// 优先级队列
function PriortyQueue(){
// element 数据项
// priorty 优先级别
function QueueElement(element,priorty){
// 保存数据,及保存优先级
this.element = element
this.priorty = priorty
}
// 封装属性
this.items = []
PriortyQueue.prototype.enqueue = function (element,priorty) {
// 创建一个QueueElement 对象
let queueElement = new QueueElement(element,priorty)
// 判断队列是否为空、
if(this.items.length === 0) {
this.items.push(queueElement)
} else {
let added = false
for(let i = 0; i < this.items.length; i++){
if(queueElement.priorty < this.items[i].priorty) {
this.items.splice(i,0,queueElement)
// 已经找到了,结束循环,就不再往下循环了
added = true
break
}
}
if (!added) {
this.items.push(queueElement)
}
}
}
// 队列删除元素 ,只能从前端删除
PriortyQueue.prototype.dequeue = function(){
return this.items.shift()
}
// 查看最前面的一个元素
PriortyQueue.prototype.front = function(){
return this.items[0]
}
// 查看队列是否为空
PriortyQueue.prototype.isEmpty = function(){
return this.items.length === 0
}
// 查看元素个数
PriortyQueue.prototype.size = function(){
return this.items.length
}
// toString方法
PriortyQueue.prototype.toString = function(){
let resultString = ''
for(let i = 0; i < this.items.length; i++){
resultString = this.items[i] + ''
}
return resultString
}
}
let q = new PriortyQueue()
// 传入数据和优先级别
q.enqueue('a',11)
q.enqueue('b',2)
q.enqueue('c',50)
console.log(q)
JavaScript封装优先级队列
最新推荐文章于 2022-07-06 15:10:40 发布
这篇博客介绍了如何创建一个优先级队列,该队列根据优先级插入和删除元素。通过`enqueue`方法添加元素,根据优先级将其插入到正确的位置,`dequeue`方法删除并返回最高优先级的元素,`front`方法查看队首元素,`isEmpty`检查队列是否为空,`size`获取队列长度,`toString`用于显示队列内容。示例展示了如何使用这个优先级队列实例。
摘要由CSDN通过智能技术生成