队列

队列 相关问题 击鼓传花问题

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. function Queue(){
  12. //属性
  13. this.items = []
  14. //方法
  15. // 1.将元素加入到队列中
  16. Queue.prototype.enqueue = function(element){
  17. this.items.push(element)
  18. }
  19. // 2.从队列中删除元素
  20. Queue.prototype.dequeue = function(){
  21. return this.items.shift()
  22. }
  23. // 3.查看前端的元素
  24. Queue.prototype.front = function(){
  25. return this.items[0]
  26. }
  27. // 4.查看队列是否为空
  28. Queue.prototype.isEmpty = function(){
  29. return this.item.length == 0
  30. }
  31. // 5.查看队列中元素的个数
  32. Queue.prototype.size = function(){
  33. return this.items.length
  34. }
  35. // 6.toString 方法
  36. Queue.prototype.toString = function(){
  37. var resultString = ''
  38. for(var i=0;i<this.items.length;i++){
  39. resultString += this.items[i] + ' '
  40. }
  41. return resultString
  42. }
  43. }
  44. // 击鼓传花
  45. function passGame(nameList,num){
  46. //1.创建一个队列结构
  47. var queue = new Queue()
  48. //2.将所有人依次加入到队列中
  49. for(var i = 0; i < nameList.length;i++){
  50. queue.enqueue(nameList[i])
  51. }
  52. // 3.开始数数字
  53. // 不是num的时候,重新加入到队列的末尾
  54. // 是num这个数字的时候 将其从队列中删除
  55. while(queue.size() > 1){
  56. for(var i =0;i<num-1;i++){
  57. // num数字之前的人重新放入到队列中末尾
  58. queue.enqueue(queue.dequeue())
  59. }
  60. // num对应这个人直接从队列中删除
  61. queue.dequeue()
  62. }
  63. // 4.获取剩下的那个人
  64. var endName = queue.front()
  65. return nameList.indexOf(endName)
  66. }
  67. names = ['lily','Lucy','Tom','Lilei','why']
  68. console.log(passGame(names,3))
  69. </script>
  70. </body>
  71. </html>

优先级队列

应用:登记的顺序,头等舱的优先级高于经济舱 / 医院的急诊科