Js实现优先队列
栈和堆基本是我们学习数据结构的必备关卡了,当你实现了堆结构以后尝试实现一下优先级队列吧!
一下是我的优先级队列代码结构-----狗尾续貂
function PriorityQueue() {
// 创建一个保存数据的对象
this.items = [];
// 由于我们现在是两个元素所以我们需要把这两个元素进行一次封装这里我们也使用构造函数进行一次封装
/*
如果我们不进行封装我们很难区分那个对那个元素封装一下
*/
function QueueElement(element, proiorty) {
this.element = element;
this.proiorty = proiorty;
}
PriorityQueue.prototype.enqueue = function (element, proiorty) {
// 我们把接收过来的两个参数传入封装函数中封装一个对象
var queueElement = new QueueElement(element, proiorty);
//如果当前队列中没有元素的话我们就直接添加
if (this.items.length == 0) {
this.items.push(queueElement);
} else {
// 创建一个状态如果当前元素都比items里面的大我们就添加到最前面就行
var flag = false;
// 如果有元素我们需要判断一下
//先遍历一下原有的元素进行全部比较一下
for (var i = 0; i < this.items.length; i++) {
// 判断一下当前元素的插入位置
// 如果当前元素的proiorty大于堆中的某个元素proiorty我们需要把它放到他的前面
if (queueElement.proiorty > this.items[i].proiorty) {
// splice--插入功能, 第一个参数(插入位置),第二个参数(0),第三个参数(插入的项)
this.items.splice(i, 0, queueElement);
flag = true;
break;
}
}
if (!flag) {
this.items.push(queueElement);
}
}
};
// 从队列中删除元素
PriorityQueue.prototype.dequeue = function () {
return this.items.shift();
};
// 查看栈顶元素
PriorityQueue.prototype.front = function () {
return this.items[0];
};
// 查看队列是否为空
PriorityQueue.prototype.isEmpty = function () {
return this.items.length == 0;
};
// 查看队列元素个数
PriorityQueue.prototype.size = function () {
return this.items.length;
};
// toString方法
PriorityQueue.prototype.toString = function () {
let Stringresult = "";
for (var i = 0; i < this.length; i++)
[(Stringresult += this.items[i])];
return Stringresult;
};
}
Test
var pq = new PriorityQueue();
pq.enqueue("d", 30);
pq.enqueue("c", 50);
pq.enqueue("a", 100);
pq.enqueue("b", 60);
pq.enqueue("e", 20);
console.log(pq.items);
Result
0:QueueElement {element: 'a', proiorty: 100}
1:QueueElement {element: 'b', proiorty: 60}
2:QueueElement {element: 'c', proiorty: 50}
3:QueueElement {element: 'd', proiorty: 30}
4:QueueElement {element: 'e', proiorty: 20}