开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 1 天,点击查看活动详情
队列的概念
队列是一种线性表,遵循从队尾存入元素,从队头删除元素。即:先进先出原则(FIFO:first in first out)。
实现队列
function Queue() {
this.item = []
// 将元素添加到队列
Queue.prototype.enqueue = function (element) {
this.item.push(element)
}
// 从队列中删除前端元素
Queue.prototype.dequeue = function () {
return this.item.shift()
}
// 查看队头元素
Queue.prototype.front = function () {
return this.item[0]
}
// 查看队列中元素的个数
Queue.prototype.length = function () {
return this.item.length
}
// toString
Queue.prototype.toString = function () {
let str = ''
this.item.forEach((ele, index) => index == this.item.length - 1 ? str += ele : str += ele + ',');
return str
}
}
const queue = new Queue()
queue.enqueue(10)
queue.enqueue(30)
queue.enqueue(20)
console.log(queue.toString());// 10,30,20
使用队列封装一个击鼓传花
function passGame(arr, num) {
// 创建队列,并向其中添加元素
const queue = new Queue()
arr.forEach(item => {
queue.enqueue(item)
});
// 遍历并删除元素
for (let i = 0; i < num - 1; i++) {
// 先删除元素,dequeue会返回被删除的元素,后enqueue在添加回去
queue.enqueue(queue.dequeue())
}
queue.dequeue()
return queue.toString()
}
const arr = ['张三', '李四', '王五', '赵六']
console.log(passGame(arr, 3)); // 赵六,张三,李四
console.log(passGame(arr, 20)); // 张三,李四,王五
优先级队列
优先级队列在插入时,会考虑该数据的优先级,所以每个元素不再是单一的数据,为数据+优先级。
//封装优先级队列
function PriorityQueue() {
//可以把这个方法理解为内部类
function QueueElement(element, priority) {
this.element = element;
this.priority = priority;
}
//封装属性
this.item = [];
//实现插入方法
PriorityQueue.prototype.enqueue = function (element, priority) {
//1.创建QueueElement对象
var qe = new QueueElement(element, priority);
//2.判断队列是否为空
if (this.item.length == 0) {
this.item.push(qe);
} else {
var added = false;
for (var i = 0; i < this.item.length; i++) {
if (qe.priority < this.item[i].priority) {
this.item.splice(i, 0, qe);
var added = true;
break;
}
}
if (!added) {
this.item.push(qe);
}
}
}
//从队列中删除前端元素
PriorityQueue.prototype.dequeue = function () {
return this.item.shift();
};
//查看前端元素
PriorityQueue.prototype.front = function () {
return this.item[0];
};
//查看队列是否为空
PriorityQueue.prototype.isEmpty = function () {
return this.item.length == 0;
};
//查看队列中元素的个数
PriorityQueue.prototype.size = function () {
return this.item.length;
};
//toStrings
PriorityQueue.prototype.toStrings = function () {
var str = '';
for (var i = 0; i < this.item.length; i++) {
str += this.item[i].element + '-' + this.item[i].priority + ' ';
}
return str;
};
}
//测试代码
var pq = new PriorityQueue();
pq.enqueue('ccc', 333);
pq.enqueue('bbb', 222);
pq.enqueue('aaa', 111);
alert(pq.toStrings());