js 算法面试题队列结构(击鼓传花进阶版)

几个朋友围成一圈,开始数数,数到某个数字的人自动淘汰,最后剩下的人就会获得胜利。

封装一个基于队列的函数

参数,所有参加的人,基于数字

结果,最终剩下的姓名

<!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>
<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.items.length == 0 
        }
        // 5.返回队列包含的元素个数
        Queue.prototype.size  = function (){
            return this.items.length
        }
        // 6.将队列内容转成字符串
        Queue.prototype.toString = function(){
            var resultString = ''
            for (const value of this.items) {
                resultString +=value +''
            }
            return resultString
        }
    }

    // var  q = new Queue()
    // q.enqueue(3)
    // q.enqueue(4)
    // q.enqueue(5)
    // q.enqueue(6)
    // alert(q)
    // alert(q.dequeue())
    // alert(q.front())
    // alert(q.isEmpty())
    // alert(q.size())
    // alert(q.toString())
    
    //面试题:击鼓传花
    function manyPlay(nameList , num){
        let queue = new Queue()
        for (const value of nameList) {
            queue.enqueue(value)
        }
        while( queue.size() > 1 ){
            for(let i = 0 ;i < num-1; i++){
                queue.enqueue(queue.dequeue())
            }
            queue.dequeue()
        }
        //取出剩下的那个人
        alert(queue.size())
        let lastName = queue.front()
        alert(lastName)
        return nameList.indexOf(lastName)
    }
    var nameList = ['Zheng','Huang','Li','Chai','Sun']
   alert( manyPlay(nameList,3))



</script>
<body>
    
</body>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值