/*
优先队列:从优先队列中删除元素时, 需要考虑优先权的限制。
数组实现队列
*/
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());