队列先进先出
常用的方法 enqueue()队尾添加新的项、dequeue()、front()、isEmpty()、size()
// 方法实现队列
function Queue() {
let items = [];
this.enqueue = function(elements) {
items.push(elements);
}
this.dequeue = function() {
return this.shift();
}
this.front = function() {
items.unshift();
}
this.isEmpty = function() {
items = [];
}
this.size = function() {
return items.length;
}
this.print = function() {
console.log(items.toString());
}
}
// es6实现队列
let Queue2 = (function() {
const items = [];
class Queue2 {
constructor(){
items.set(this, []);
}
enqueue(elements){
let q = items.get(this);
q.push(elements);
}
dequeue(){
let q = items.get(this);
let r = q.pop();
return r ;
}
}
});
优先队列
function PriorityQueue() {
let items = [];
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
this.enqueue = function (element , priority) {
let queue = new QueueElement(element, priority);
let add = false;
for (var i = 0; i < items.length; i++) {
if(queue.priority < items[i].priority){
items.splice(i, 0, element);
add = true;
break;
}
}
if (!add) {
items.push(elements);
}
};
this.print = function () {
for (var i = 0; i < items.length; i++) {
console.log(`$(items[i].element)-$(items[i].priority)`);
}
}
}
实例 队列实现击鼓传花
function jigucguanhua(namelist, time) {
let queue = new Queue();
for (var i = 0; i < namelist.length; i++) {
queue.enqueue(namelist[i]);
}
let eliminated = '';
while(queue.size() > 1) {
for (var i = 0; i < queue.length; i++) {
queue.enqueue(queue.enqueue());
}
eliminated = queue.dequeue()
console.log(eliminated + 'dkvnodfvn')
}
return queue.dequeue();
}