队列

队列是什么?

image-20200429091554941

队列实现操作:

image-20200429091703742

新建Html引入js:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script src="./02_队列.js"></script>
</head>
<body>
</body>
</html>

队列操作.js:

let Queue = function(){
let items = []

//入队
this.enqueue = (element)=>{
return items.push(element)
}

//出队
this.dequeue = ()=>{
return items.shift()
}

//查询列头
this.front = ()=>{
return items[0]
}

//检查队列是否为空
this.isEmpty = ()=>{
return items.length===0
}

//获取队列长度
this.size = ()=>{
return items.length
}

}

实际应用例子:

  • 循环队列:击鼓传花
//循环队列例子:击鼓传花
let arr = ['a','b','c','d','e','f']
let drinking_game = function(arr,numbers){
let queue = new Queue()
for(let j=0;j<arr.length;j++){
queue.enqueue(arr[j]);
}

while(queue.size()>1){
for(let i =0;i<numbers-1;i++){
queue.enqueue(queue.dequeue())
}
let getout = queue.dequeue()
console.log(`本次出局的是${getout}`)
}
let result = queue.dequeue()
console.log(`最终剩下的是${result}`)
}
  • 优先队列例子:VIP排队
let PriorityQueue = function(name,priority){
let items = []
let Queueitems = function(name,priority){
this.name = name
this.priority = priority
}
this.enqueue = function(name,priority){
//判断是否插入
let queuebolean = false
let queueitems = new Queueitems(name,priority)
for(let i=0;i<items.length;i++){
if(queueitems.priority>items[i].priority){
items.splice(i,0,queueitems)
queuebolean = true
break;
}
}

if(!queuebolean){
items.push(queueitems)
}
}

this.getitems =function(){
return items
}

}