Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数据结构--队列 #27

Open
lznbuild opened this issue Jun 15, 2020 · 0 comments
Open

数据结构--队列 #27

lznbuild opened this issue Jun 15, 2020 · 0 comments

Comments

@lznbuild
Copy link
Owner

队列的模拟实现

先进先出(排队打饭)

class Queue {
  constructor() {
    this.queue = []
  }

  // 队列尾部添加元素
  enQueue(item) {
    this.queue.push(item)
  }

  // 删除队列头的第一个元素
  deQueue() {
    return this.queue.shift()
  }

  // 获取队头的第一个元素
  getHeader() {
    return this.queue[0]
  }

  // 获取队列的长度
  getLength() {
    return this.queue.length
  }

  // 判断队列是否为空
  isEmpty() {
    return this.getLength() === 0
  }
}

相关算法题

a-f 6 个人坐在一起围成一个圈,玩击鼓传花游戏,每传递花3次,就淘汰一个人,最后剩余的一个人为胜者,计算谁为胜者。

// 击鼓传花 循环队列
var names = ['a','b','c','d','e','f'];
// 游戏规则
var number = 3; // 传3次就淘汰一个人

function chuanhua (names, number) {
  var q = new Queue(); // 使用上面实现的队列 
  for(var i=0;i<names.length;i++){
    q.enQueue(names[i])// 所有项入队列
  }
  
  var taotai;
  // 小于等于1,胜者出现
  while(q.getLength()>1){
    for(var i=0;i<number-1;i++){
      q.enQueue(q.deQueue()) // 先出队列,再进队列,相当于把队列的number前几项 放到后面到后面
    }
    taotai=q.deQueue(); // 删除number对应的项
    console.log('淘汰----'+taotai)
  }
  return q.deQueue() // 胜者
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant