javascript 实现优先级队列
//封装优先级队列
function PriorityQueue() {
//在优先级队列创建一个内部类
function QueueElement(element,priority) {
this.element = element
this.priority = priority
}
this.items = []
//实现插入的方法
PriorityQueue.prototype.enQueue = function (element,priority) {
let queueElement = new QueueElement(element,priority)
//判断队列是否为空
if (this.items.length === 0) {
this.items.push(queueElement) //为空直接插入
} else { //不为空的情况
let flag = false // 判断是否在遍历的过程插入
for (let i = 0; i < this.items.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i,0,queueElement) //找到合适的地方 进行插入
flag = true
break
}
}
if (!flag) { //如果在遍历的过程中没插入 说明该元素的优先级最小 直接插入到最后
this.items.push(queueElement)
}
}
}
//前端删除队列元素
PriorityQueue.prototype.delQueue = function () {
return this.items.shift()
}
//查看前端的元素
PriorityQueue.prototype.front = function () {
return this.items[0]
}
//查看队列是否为空
PriorityQueue.prototype.isEmpty = function () {
return this.items.length === 0
}
//查看队列中元素的个数
PriorityQueue.prototype.size = function () {
return this.items.length
}
//将队列中的元素转化为字符串
PriorityQueue.prototype.toString = function () {
let resultString = ''
for (let i = 0 ; i < this.items.length; i++) {
resultString += this.items[i].element + '-' + this.items[i].priority + ''
}
return resultString
}
}
const pq = new PriorityQueue()
pq.enQueue('a',8)
pq.enQueue('c',1)
pq.enQueue('d',100)
pq.enQueue('e',23)
console.log(pq)
结果
PriorityQueue {
items: [
QueueElement { element: 'c', priority: 1 },
QueueElement { element: 'a', priority: 8 },
QueueElement { element: 'e', priority: 23 },
QueueElement { element: 'd', priority: 100 }
]
}