javascript 实现优先级队列

本文介绍了如何使用JavaScript来实现优先级队列这一数据结构,通过实例代码详细解析其工作原理和操作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

javascript 实现优先级队列

//封装优先级队列
function PriorityQueue() {
    //在优先级队列创建一个内部类
    function QueueElement(element,priority) {
        this.element = element
        this.priority = priority
    }

    this.items = []

    //实现插入的方法
    PriorityQueue.prototype.enQueue = function (element,priority) {
        let queueElement = new QueueElement(element,priority)
        //判断队列是否为空
        if (this.items.length === 0) {
            this.items.push(queueElement) //为空直接插入
        } else { //不为空的情况
            let flag = false // 判断是否在遍历的过程插入
            for (let i = 0; i < this.items.length; i++) {
                if (queueElement.priority < this.items[i].priority) {
                    this.items.splice(i,0,queueElement) //找到合适的地方 进行插入
                    flag = true
                    break
                }
            }
            if (!flag) { //如果在遍历的过程中没插入 说明该元素的优先级最小 直接插入到最后
                this.items.push(queueElement)
            }
        }
    }
    //前端删除队列元素
    PriorityQueue.prototype.delQueue = 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
    }
    //将队列中的元素转化为字符串
    PriorityQueue.prototype.toString = function () {
        let resultString = ''
        for (let i = 0 ; i < this.items.length; i++) {
            resultString += this.items[i].element + '-' + this.items[i].priority + ''
        }
        return resultString
    }
}

const pq = new PriorityQueue()

pq.enQueue('a',8)
pq.enQueue('c',1)
pq.enQueue('d',100)
pq.enQueue('e',23)

console.log(pq)

结果

PriorityQueue {
  items: [
    QueueElement { element: 'c', priority: 1 },
    QueueElement { element: 'a', priority: 8 },
    QueueElement { element: 'e', priority: 23 },
    QueueElement { element: 'd', priority: 100 }
  ]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值