特点:先进先出
基本队列
class Queue{
constructor(){
this.list = list || []//使用数组模拟
}
add(item){ //在尾部添加,只需要配合在头部删除即可实现队列
this.list.push(item)
}
pop(){//从头部删除
return this.list.pop()
}
size(){//查看队列大小
return this.list.length
}
print(){//查看队列
return this.list
}
first(){//查看队列第一个元素
return this.list[0]
}
isEmpty(){//判断队列是否为空
return Boolean(this.list.length)
}
}
优先队列
class PriorityQueue extends Queue{
constructor(list){
super(list)
}
add(item,priority){ //重写add,加入优先级
let v = {
item,
priority
}
if(this.isEmpty()){ //若为空,则直接push即可
this.list.push(v)
}else{
let exist = false
for(let i=0;i
if(priority
this.list.splice(i,0,v)
exist = true
break
}
if(!exist){
this.list.push(v) //如果优先级最高,则直接放到尾部
}
}
循环队列(击鼓传花)
class CircleQueue extends Queue{
constructor(list,stopIndex){
super(list)
this.stopIndex = stopIndex || 0
this.result = []
this.winner = undefined
return this.run()
}
run(){
this.order = 0
while(this.size()>1){ //最终剩下的那个就是循环结束后的值
for(let i=0;i
this.add(this.pop()) //在未停止前,不断将第一个元素移动到尾部
}
this.result.push({
name:this.pop(),
order:this.order++
})
this.winner = this.pop()
return {
winner:this.winner,
result:this.result
}
}