队列特点:遵循先进先出(FIFO)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。 创建队列
首先,创建一个类来表示一个队列。
-
enqueue(element):向队列尾部添加一个新的项。
-
dequeue():移除队列的第一项,并返回被移除的项。
-
front():返回队列中的第一个元素,队列不做任何变动。
-
isEmpty():判断队列是否为空。
-
size():返回队列长度。
class queue { constructor(){ this.data=[] } enqueue(item){ this.data.push(item) } dequeue(){ this.data.shift() } get front(){ return this.data[0] } get isEmpty(){ this.data.length==0 } get size(){ return this.data.length } }const Queue = new queue() Queue.enqueue(2) Queue.enqueue(3) Queue.dequeue() console.log(Queue.size); console.log(Queue.front); Queue.isEmpty() console.log(Queue.size);
优先队列
优先队列元素的添加和移除是基于优先级的。拿医院候诊室举例,医生会优先处理病情比较严重的患者。
class queue {
constructor(){
this.data=[]
}
enqueue(item){
this.data.push(item)
}
dequeue(){
this.data.shift()
}
get front(){
return this.data[0]
}
get isEmpty(){
this.data.length==0
}
get size(){
return this.data.length
}
}
class QueueElement {
constructor(element,priority){
this.element = element;
this.priority = priority;
}
}
class PriorityQueue extends queue{
constructor(){
super()
}
enqueue(element,priority){
let queueElement=new QueueElement(element,priority)
//当队列为空,直接添加
if (this.isEmpty()){
this.data.push(queueElement);
}else {
let added=false;
for (let i=0;i<this.data.length;i++){
if (queueElement.priority < this.data[i].priority){
this.data.splice(i, 0, queueElement);
added=true;
break;
}
}
if (!added){
this.data.push(queueElement);
}
}
}
}