guyuezhai / interviewSummary

some summary of interview
0 stars 0 forks source link

队列实现 #2

Open guyuezhai opened 4 years ago

guyuezhai commented 4 years ago

实现队列,具有以下功能

guyuezhai commented 4 years ago

优先级队列

function PriorityQueue() {
     let items=[]
     function QueueElement(item,priority) {
         this.item=item;
         this.priority=priority
     }
     this.enqueue=function(item,priority){
        let element=new QueueElement(item,priority)
        let add=false,length=items.length;
        for(let i=0;i<length;i++){
            if(element.priority<items[i].priority){
                items.splice(i,0,element)
                add=true
                break
            }
        }
        if(!add){
            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(){
        let length=items.length
        for(let i=0;i<length;i++){
            console.log("item: %s-priority: %s",items[i].item,items[i].priority)
        }

    }
 }
guyuezhai commented 4 years ago

队列的应用

击鼓传花

function hotPotato(nameList,num) {
     let queue=new Queue()
     let length=nameList.length
     for(let i=0;i<length;i++){
        queue.enqueue(nameList[i])
     }

     while(queue.size()>1){
         for(let i=0;i<num;i++){
             queue.enqueue(queue.dequeue())
         }
         let name=queue.dequeue()
         console.log(" %s 已经被淘汰",name)
     }
     return queue.dequeue()
 }

 let winner=hotPotato(['张三','李四','王五','王麻子','隔壁老王'],4)
 console.log('最终胜出者是---> %s',winner)

打印结果

隔壁老王 已经被淘汰 张三 已经被淘汰 王五 已经被淘汰 王麻子 已经被淘汰 最终胜出者是---> 李四