zoukankan      html  css  js  c++  java
  • js封装一个队列

    // 基于数组封装一个队列
    function Queue() {
        this.items = [];
        // 将数据存入队列中
        Queue.prototype.entryQueue = function (ele) {
            return this.items.push(ele)
        }
        // 数据出队列
        Queue.prototype.outQueue = function () {
            return this.items.shift()
        }
        // 查看队列的第一个数据信息
        Queue.prototype.front = function () {
            return this.items[0]
        }
        // 判断队列是否为空
        Queue.prototype.isEmpty = function () {
            return this.items.length == 0
        }
        // 队列的长度
        Queue.prototype.size = function () {
            return this.items.length
        }
        // toString
        Queue.prototype.toString = function () {
            let str = '';
            for (let i = 0; i < this.items.length; i++) {
                str += this.items[i] + ' '
            }
            return str
        }
    }
    
    let q = new Queue();
    q.entryQueue(11);
    q.entryQueue(22);
    q.entryQueue(33);
    q.entryQueue(44);
    // 击鼓传花
    function passName(nameList, num) {
        let q = new Queue();
        // 将数据依次放入队列中
        for (let i = 0; i < nameList.length; i++) {
            q.entryQueue(nameList[i])
        }
        // 游戏开始,当只剩一人时,游戏结束
        while (q.size() > 1) {
            // 将没被淘汰的依次进行出列,入列
            for (let j = 0; j < num - 1; j++) {
                q.entryQueue(q.outQueue())
            }
            // 淘汰的出列
            q.outQueue()
        }
        let name = q.front();
        return '游戏胜利的是' + name + ',他所在的位置是' + nameList.indexOf(name)
    
    }
    
    let nameList = ['lisi', 'zhaoGao', 'feifei', 'tom', 'jay', 'maria'];
    console.log(passName(nameList, 5));  // 游戏胜利的是lisi,他所在的位置是0
  • 相关阅读:
    c#中@的3种作用
    iOS7 各种问题解决
    时钟
    京东APP(部分)-安卓
    博弈取石子
    博弈取牌
    年月日
    猪(恶作剧程序)
    字符统计
    奇偶类约瑟夫
  • 原文地址:https://www.cnblogs.com/cyf666cool/p/14837122.html
Copyright © 2011-2022 走看看