实现优先级队列主要有两方面需要考虑
- 封装元素和优先级
- 添加元素时,将新插入元素的优先级和队列中已经存在的元素优先级进行比较,以获得自己正确的位置
核心是对插入队列方法enqueue的封装
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 (let i=0; i<this.items.length; i++) {
if (priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement)
added = true
break;
}
}
if (!added) {
this.items.push(queueElement)
}
}
return 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
}
PriorityQueue.prototype.size = function() {
return this.items.length
}
PriorityQueue.prototype.toString = function() {
let resultString = ''
for (let i of this.items) {
resultString += `${i.element}-${i.priority} `
}
return resultString
}
}
const pq = new PriorityQueue()
pq.enqueue('abc', 111)
pq.enqueue('cba', 200)
pq.enqueue('nba', 50)
pq.enqueue('nba', 66)
console.log(pq.toString()) // 结果:nba-50 nba-66 abc-111 cba-200