文章出處

隊列遵循FIFO (First In First Out)原則。

普通隊列

      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());
        }
      }

  優先級隊列

function PriorityQueue() {
        var items=[];
        function QueueElement(element,priority) {
          this.element=element;
          this.priority=priority;
        }
        // priority 數值越大,優先級越低
        this.enqueue=function (element,priority) {
          var queueElement=new QueueElement(element,priority);
          if(this.isEmpty()){
            items.push(queueElement);
          }else{
            var added=false;
            for (var i = 0; i < items.length; i++) {
              if(queueElement.priority<items[i].priority){
                items.splice(i,0,queueElement);
                added=true;
                break;
              }
            }
            if(!added){
              items.push(queueElement);
            }
          }
        }
        // 移除隊列最后一個
        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(JSON.stringify(items));
        }
}

通過擊鼓傳花演示循環隊列

function hotPotato(nameList,num){
        var queue=new Queue(),eliminated="";
        for (var i = 0; i < nameList.length; i++) {
          queue.enqueue(nameList[i]);
        }
        while (queue.size()>1) {
          for (var i = 0; i < num; i++) {
            queue.enqueue(queue.dequeue());
          }
          eliminated=queue.dequeue();
          console.log(eliminated+"被淘汰");
        }
        return queue.dequeue();
 }

  

  


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()