队列 先进先出
1、创建对列
function Queue() {
//这里是属性和方法
}
需要一个用于存储对列中元素的数据结构 我们可以使用数组let items=[];
对列的方法:
①enqueue(element(s)):向队列尾部添加一个(或多个)新的项。
this.enqueue = function(element){
items.push(element);
};
②dequeue():移除队列的第一(即排在队列最前面的)项,并返回被移除的元素。
this.dequeue = function(){
return items.shift();
};
③front():返回队列中第一个元素——最先被添加,也将是最先被移除的元素。队列不
做任何变动(不移除元素,只返回元素信息——与Stack类的peek方法非常类似)。
this.front = function(){
return items[0];
};
④isEmpty():如果队列中不包含任何元素,返回true,否则返回false。
this.isEmpty = function(){
return items.length == 0;
};
⑤size():返回队列包含的元素个数,与数组的length属性类似。
this.size = function(){
return items.length;
};
⑥print 打印元素
this.print = function(){
console.log(items.toString());
};
使用queue类 let queue = new Queue();
2、优先队列
function PriorityQueue() {
let items = [];
function QueueElement(element, priority) { /*要向PriorityQueue
添加元素,需要创建一个特殊的元素。这个元素包含了要添加到队列的元素
(它可以是任意类型)及其在队列中的优先级。*/
this.element = element;
this.priority = priority;
}
this.enqueue = function (element, priority) {
let queueElement = new QueueElement(element, priority);
let added = false;
for (let i = 0; i < items.length; i++) { //遍历对列中的元素
if (queueElement.priority < items[i].priority) {
/*当找到一个比要添加的元素的priority值更大(优先级更低)的项时,
就把新元素插入到它之前*/
items.splice(i, 0, queueElement); //元素插入操作
added = true;
break;
}
}
if (!added) {
items.push(queueElement); /*如果优先级查找失败即 要插入
元素的优先级大于对列中的每一个元素 那么久直接追加在 对列的最后*/
}
};
this.print = function () {
for (let i = 0; i < items.length; i++) {
console.log(`${items[i].element} - ${items[i].priority}`);
}
};
//其他方法和默认的Queue实现相同
}
//调用
let priorityQueue = new PriorityQueue();
priorityQueue.enqueue("John", 2);
priorityQueue.print();
3、击鼓传花 循环队列
function Queue() {
//这里是属性和方法
let items = [];
//添加元素
this.add = function (element) {
items.push(element);
};
//移除元素 先进先出 把最先添加的项移除
this.del = 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 hotPotato(nameList, num) {
let queue = new Queue(); // {1}
for (let i = 0; i < nameList.length; i++) {
queue.add(nameList[i]); // 把里面的名字全都加入队列
}
let eliminated = '';
while (queue.size() > 1) {
for (let i = 0; i < num; i++) {
queue.add(queue.del()); /* 给定一个数字,然后迭代
队列。从队列开头移除一项,再将其添加到队列末尾 */
}
eliminated = queue.del();/* 模拟击鼓传花(如果你把花传给
了旁边的人,你被淘汰的威胁立刻就解除了)。一旦传递次数达到
给定的数字,拿着花的那个人就被淘汰了*/
console.log(eliminated + '在击鼓传花游戏中被淘汰。');
}
return queue.del();// 最后只剩下一个人的时候,这个人就是胜者
}
let names = ['John', 'Jack', 'Camila', 'Ingrid', 'Carl'];
let winner = hotPotato(names, 7);
console.log('The winner is: ' + winner);