javascript数据结构与算法笔记(四):循环队列

版权声明:转载请注明出处 https://blog.csdn.net/wushichao0325/article/details/84972296

javascript数据结构与算法笔记(四):循环队列

一:简介

循环队列是指队列头元素的移除会追加到队列的尾部。我们此次拿一个例子来实现循环队列,例子名就是模拟民间游戏击鼓传花即:数人或几十人围成圆圈坐下,其中一人拿花(或一小物件);另有一人背着大家或蒙眼击鼓(桌子、黑板或其他能发出声音的物体),鼓响时众人开始依次传花,至鼓停止为止。此时花在谁手中(或其座位前),谁就上台表演节目(多是唱歌、跳舞、说笑话;或回答问题、猜谜、按纸条规定行事等);偶然如果花在两人手中,则两人可通过猜拳或其它方式决定负者。

二:ES6版Queue类

1.使用WeakMap类声明PriorityQueue类
具体原因可以参照:https://blog.csdn.net/wushichao0325/article/details/84969725

let Queue=(function(){
    const items=new WeakMap();
    class Queue{
        constructor(){
            items.set(this,[]);
        }
        enqueue(element){
            let q=items.get(this);
            q.push(element);
        }
        dequeue(){
            let q=items.get(this);
            let r=q.shift();
            return r;
        }
        front(){//查看队列头元素
            let q=items.get(this);
            return q[0];
        }
        isEmpty(){
            let q=items.get(this);
            return q.length==0;
        }
        size(){
            let q=items.get(this);
            return q.length;
        }
        print(){
            let q=items.get(this);
            console.log(q.toString())
        }
    }
    return Queue;
})();

2.循环队列实现与运用

function circulQueue(list,num){
    let queue=new Queue();
    for(let i=0;i<list.length;i++){
        queue.enqueue(list[i]);
    }
    let endvalue='';
    let circuls=0;
    while(queue.size()>1){
        circuls++;
        for(let i=0;i<num;i++){
            queue.enqueue(queue.dequeue());//形成循环队列
        }
        endvalue=queue.dequeue();
        console.log(`${endvalue}在第${circuls}轮淘汰`);
    }
    return queue.dequeue();
}

注:num模拟规定敲几下鼓就停止的条件。
3.使用

let names=['john','jack','tom','xiaohong','xiaoming','huahua'];
let win=circulQueue(names,10);
console.log(`胜利者为:${win}`)

猜你喜欢

转载自blog.csdn.net/wushichao0325/article/details/84972296
今日推荐