数据结构3-优先级队列 2018-08-14 数据结构 Comments 优先级队列 优先级队列的优点 队列的有点是先进先出,这导致我们有的数据比较重要,却不能提前出来。优先级队列主要解决了这一痛点。 优先级实现 封装的元素要和优先级放在一起 添加元素的时候,要遍历优先级比较,进行存储 实现 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354function PriorityQeueu(){ // 创建一个对象,存储元素和优先级 function Node(element,priority){ this.element = element; this.priority = priority; } //数组存储对象 var item = []; this.length = 0; // 数组是否为空 this.isEmpty = function(){ return this.length === 0; } // 添加元素 this.enqueue = function(element,priority){ var node = new Node(element,priority); // 如果数组是空的,那么就是第一个元素,直接加进来即可。 if(this.isEmpty()){ items.push(node); }else{ //判断是否已经加入数组 var added = false; // 遍历查询是否优先级比较高 for(var i=0;i<this.length;i++){ if(node.priority > item[i].priority){ //数字越高,优先级越高,进行插入 items.splice(i,0,node); added = true; break; } } // 如果都没有,说明数字是最小的,优先级是最低的,加在最后面。 if(!added){ items.push(node); } } } this.dequeue = function(){ return items.shift(); } }// 测试pe = new PriorityqQueue()pe.enqueue('a',1);pe.enqueue('b',2);pe.enqueue('c',3);pe.enqueue('d',4);alert(pe.dequeue().ele);alert(pe.dequeue().ele);alert(pe.dequeue().ele);alert(pe.dequeue().ele);