队列-击鼓传花

1-创建队列对象

  function Queue() {
    var items = [];
      //属性和方法
    this.enqueue = function (element) {//队尾添加元素
        items.push(element);
    }

    this.dequeue = function () {//删除第一个元素
         return items.shift();
    }

    this.front = function () {//返回第一个元素
        return items[0];
    }

    this.isEmpty = function () {//判断为空不
        return items.length == 0;
    }

    this.size = function () {//队列长度
        return items.length;
    }

    this.print = function () {//打印队列
        console.log(items.toString());
    }   
}

2-击鼓传花函数

function hotPotato(nameList, num){//num就是传花几次
    var queue = new Queue();

    for(var i = 0; i<nameList.length; i++){
       queue.enqueue(nameList[i]);//名字全部加入队列
    }

    var eleminated = '';
     while(queue.size() > 1){
       for(var i =0; i<num; i++){
           queue.enqueue(queue.dequeue());//队列开始移除一项,再加入至队尾
        }

        eleminated = queue.dequeue();//循环次数num结束,拿着花的淘汰,
                                    //即队列第一个人,所以用dequeue()
       console.log(eleminated+"被移除");
     }

     return queue.dequeue();//剩下的就是胜者,其实就一个人。
}

3-调用函数

var names = ['John', 'Jack', 'Camila', 'Ingrid', 'Carl'];
var winner = hotPotato(names, 7);
console.log("胜利者: " + winner);     

4-结果

结果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容