Skip to content

Latest commit

 

History

History
81 lines (71 loc) · 1.95 KB

03.队列.md

File metadata and controls

81 lines (71 loc) · 1.95 KB

3. 队列

队列是遵循先入先出(FIFO)原则的有序的项。队列在尾部添加新元素,并在顶部移除元素。最新添加的元素必须排列在队列的尾部

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);
}
function dequeue(){  
  return this.dataStore.shift();
}
function front(){  
  return this.dataStore[0];
}
function back(){  
  return this.dataStore[this.dataStore.length-1];
}
function empty(){  
  if(this.dataStore.length == 0)return true;
  else return false;
}
function toString(){  
  var reStr = "";
  for (var i = 0; i < this.dataStore.length; i++) {
    reStr += this.dataStore[i] + "\n";
  }
  return reStr;
}

算法:实现方块舞的舞伴分配问题

/* 实现方块舞的舞伴分配问题 */

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

function dequeue() {
  var priarity = 0;
  for (var i = 1; i < this.dataStore.length; ++i) {
    if (this.dataStore[i].code > this.dataStore[priarity].code) {
      priarity = i;
    }
  }
  return this.dataStore.splice(priarity, 1);
}

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 pa = new Patient("小王", 1);
var pa1 = new Patient("小张", 4);
var pa2 = new Patient("小明", 9);
var pa3 = new Patient("小红", 3);

var quePatient = new Queue();
quePatient.enqueue(pa);
quePatient.enqueue(pa1);
quePatient.enqueue(pa2);
quePatient.enqueue(pa3);

console.log("第一个人" + quePatient.dequeue());
console.log(quePatient.toString());