隊列是遵循FIFO(First In First Out,先進先出,也稱爲先來先服務)原則的一組有序的項。 隊列在尾部添加新元素,並從頂部移除元素。最新添加的元素必須排在隊列的末尾。 在現實中,最多見的隊列的例子就是排隊:bash
// 先進先出
function Queue() {
const items = [];
this.enqueue = (...ele) => items.push(...ele);
this.dequeue = () => items.shift();
this.front = () => items[0];
this.isEmpty = () => !items.length;
this.size = () => items.length;
this.print = () => console.log('items => ',items);
}
const queue = new Queue();
queue.enqueue(1,2,3,4);
queue.print();
複製代碼
// 優先隊列: 優先數字大的
function PriorityQueue(ele, priority) {
const items = [];
function QueueElement(ele, priority) {
this.ele = ele;
this.priority = priority;
}
this.enqueue = function(ele, priority) {
const queueEle = new QueueElement(ele, priority);
if (this.isEmpty()) {
return items.push(queueEle);
}
const index = items.findIndex((item) => queueEle < item.priority);
index !== -1 ? items.splice(index, 0, queueEle) : items.push(queueEle);
return items.length;
}
}
複製代碼