优先级队列

281 阅读1分钟
  • 优先级队列, 在插入一个元素的时候会考虑该数据的优先级.(和其他数据优先级进行比较)

比较完成后, 可以得出这个元素正确的队列中的位置. 其他处理方式, 和队列的处理方式一样

image.png

  • 优先级队列代码实现
 // 加入新节点
            enqueue(ele, priority) {
                // 创建新节点 
                let newnode = {
                    data: ele,
                    priority: priority
                }
                if (this.item.length == 0) { //空队列,直接加节点 
                    this.item.push(newnode)
                } else { //非空队列
                    //   判断元素是添加在队列中还是队尾
                    let isAdd = false
                    for (let i = 0; i < this.item.length; i++) { //与队列中的元素依次比较优先级
                        if (newnode.priority < this.item[i].priority) { //新节点的优先级小于队列中元素的优先级
                            this.item.splice(i, 0, newnode); //将新节点插入到队列中
                            isAdd = true;
                            break
                        }  
                    }
                     // 循环遍历结束都没有比新节点要小的元素,直接添加到队列的最后
                     if(!isAdd){
                        this.item.push(newnode)
                    }
                }
            }
        }
        var lu=new PriorityQueue()
        lu.enqueue("luhan",7)
        lu.enqueue("sehun",94)
        lu.enqueue("lay",10)
        console.log(lu);

image.png