队列
队列 相关问题 击鼓传花问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Queue(){
//属性
this.items = []
//方法
// 1.将元素加入到队列中
Queue.prototype.enqueue = function(element){
this.items.push(element)
}
// 2.从队列中删除元素
Queue.prototype.dequeue = function(){
return this.items.shift()
}
// 3.查看前端的元素
Queue.prototype.front = function(){
return this.items[0]
}
// 4.查看队列是否为空
Queue.prototype.isEmpty = function(){
return this.item.length == 0
}
// 5.查看队列中元素的个数
Queue.prototype.size = function(){
return this.items.length
}
// 6.toString 方法
Queue.prototype.toString = function(){
var resultString = ''
for(var i=0;i<this.items.length;i++){
resultString += this.items[i] + ' '
}
return resultString
}
}
// 击鼓传花
function passGame(nameList,num){
//1.创建一个队列结构
var queue = new Queue()
//2.将所有人依次加入到队列中
for(var i = 0; i < nameList.length;i++){
queue.enqueue(nameList[i])
}
// 3.开始数数字
// 不是num的时候,重新加入到队列的末尾
// 是num这个数字的时候 将其从队列中删除
while(queue.size() > 1){
for(var i =0;i<num-1;i++){
// num数字之前的人重新放入到队列中末尾
queue.enqueue(queue.dequeue())
}
// num对应这个人直接从队列中删除
queue.dequeue()
}
// 4.获取剩下的那个人
var endName = queue.front()
return nameList.indexOf(endName)
}
names = ['lily','Lucy','Tom','Lilei','why']
console.log(passGame(names,3))
</script>
</body>
</html>
优先级队列
应用:登记的顺序,头等舱的优先级高于经济舱 / 医院的急诊科