数据结构与算法javascript描述(二) 优先队列实例

/* 
优先队列:从优先队列中删除元素时, 需要考虑优先权的限制。
数组实现队列
*/
function Queue(){
     this.dataStore = [];
     this.enqueue = enqueue;
     this.dequeue = dequeue;
     this.front = front;
     this.back = back;
     this.toString = toString;
     this.empty = empty;
    }
    function enqueue(element){
        this.dataStore.push(element);
    }
//优先码的值最小的元素优先级最高。  dequeue() 方法遍历队列的底层存储数组, 从中找出优先码最低的元素, 然后使用数组的 splice() 方法删除优先级最高的元素。
    function dequeue(){
        var priority = this.dataStore[0].code;
        for(var i = 1; i<this.dataStore.length; ++i){
          if (this.dataStore[i].code < priority){
              priority = i;
          }
        }
       return this.dataStore.splice(priority,1);
    }


    function front(){

       return this.dataStore[0];

    }
    function back(){
        return this.dataStore[this.dataStore.length-1];
    }
    function toString(){
        var retStr = "";
        for (var i=0;i<this.dataStore.length;++i){
            retStr += this.dataStore[i]+"\n";
        }
        return retStr;

    }
    function empty(){
        if(this.dataStore.length == 0){
            return true;
        }
        else{
            return false;

        }
    }

function Patient(name,code){
    this.name = name;
    this.code = code;
}



function toString(){
   var retStr = "";
   for(var i = 0;i<this.dataStore.length;++i ){
    retStr +=this.dataStore[i].name + "code: "+this.dataStore[i].code+"n";
   }
 return retStr;
}

测试

//优先队列的实现

var p = new Patient("dwx",5);
var ed = new Queue();
ed.enqueue(p);
p = new Patient("wbw",4);
ed.enqueue(p);
p = new Patient("czb",6);
ed.enqueue(p);
p = new Patient("wl", 1);
ed.enqueue(p);
p = new Patient("hdw",1);
ed.enqueue(p);
console.log(ed.toString());
var seen = ed.dequeue();
console.log("Patient being treated: " + seen[0].name );
console.log("Patient waiting to be seen: ")
console.log(ed.toString());
var seen = ed.dequeue();
console.log("Patient being treated: " +seen[0].name);
console.log("Patients waiting to be seen :")
console.log(ed.toString());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值