主要特点
- 普通队列插入元素会从队尾添加,并且只能从队首删除,而且要等前面元素都处理完才能处理
- 优先级队列插入元素时会考虑优先级,和其他元素进行优先级比较,再放入正确的位置
- 每个元素包括数据和优先级
- 添加时根据优先级放入正确的位置
生活场景
- 机场登机,头等舱,经济舱
- 去医院的急诊号比其他优先
- 计算机中也会用优先级队列进行任务顺序的排列,决定该线程在队列中被处理的次序
主要实现思路
- 将数据和优先级封装成一个元素
class QueueElement {
constructor(element,priority) {
this.element = element
this.priority = priority
}
}
- 添加元素时,将要添加的元素优先级和已存在的元素优先级进行比较,获得正确位置
enqueue(element,priority) {
let queueElement = new QueueElement(element,priority)
if(this.isEmpty()) {
this.items.push(queueElement)
} else {
let added = false
for(let i = 0; i < this.size(); i++) {
if(this.items[i].priority > queueElement.priority) {
this.items.splice(i,0,queueElement)
added = true
break
}
}
if(!added) {
this.items.push(queueElement)
}
}
}
- 其余代码和之前的队列一样
class PriorityQueue {
constructor() {
this.items = []
}
enqueue(element,priority) {
let queueElement = new QueueElement(element,priority)
if(this.isEmpty()) {
this.items.push(queueElement)
} else {
let added = false
for(let i = 0; i < this.size(); i++) {
if(this.items[i].priority > queueElement.priority) {
this.items.splice(i,0,queueElement)
added = true
break
}
}
if(!added) {
this.items.push(queueElement)
}
}
}
dequeue() {
return this.items.shift()
}
front() {
return this.items[0]
}
size() {
return this.items.length;
}
isEmpty() {
return this.size() === 0
}
toString() {
let res = ''
for (var i = 0; i < this.size(); i++) {
res += this.items[i].element + ':' + this.items[i].priority + ','
}
console.log(res)
}
}