数据结构-优先级队列

优先级队列

普通队列:

普通队列插入一个元素,数据会被放在末端,处理它前面所有的元素才会处理它

优先级队列:

优先级队列在插入的时候会考虑数据的优先级,和其他数据优先级进行比较,然后放入到正确的位置。
除此之外,优先级队列的其他处理方式和普通队列的处理方式一样。

封装优先级队列

用数组进行封装

 // 封装优先级队列
    function PriorityQueue() {
        this.items = []

        // 封装一个新的构造函数, 用于保存元素和元素的优先级
        function QueueElement(element, priority) {
            this.element = element
            this.priority = priority
        }

        // 1、添加元素的方法
        PriorityQueue.prototype.enqueue = function (element, priority) {
            // 1.根据传入的元素, 创建新的QueueElement
            var queueElement = new QueueElement(element, priority);

            // 2.获取传入元素应该在正确的位置
            if (this.isEmpty()) {
                this.items.push(queueElement);
            } else {
                var added = false
                for (var i = 0; i < this.items.length; i++) {
                    // 注意: 这里是数字越小, 优先级越高
                    if (queueElement.priority < this.items[i].priority) {
                        this.items.splice(i, 0, queueElement);
                        added = true;
                        break;
                    }
                }

                // 遍历完所有的元素, 优先级都大于新插入的元素时, 就插入到最后
                if (!added) {
                    this.items.push(queueElement);
                }
            }
        }

        // 2、delete queue方法
        PriorityQueue.prototype.dequeue = function () {
            return this.items.shift();
        }

        // 3、查看队列中的第一个元素
        PriorityQueue.prototype.front = function () {
            return this.items[0];
        }

        // 4、查看队列是否为空
         PriorityQueue.prototype.isEmpty = function () {
            return this.items.length == 0;
        }

        // 5、查看队列中元素的个数
        PriorityQueue.prototype.size = function () {
            return this.items.length;
        } 
        // 6、toString方法
        PriorityQueue.prototype.toString = function(){
            var resultString = '';
            for(var i = 0; i < this.items.length; i++){
                resultString += this.items[i].element + '-' + this.items[i].priority + ' '
            }
            return resultString
        }
    }

    // 创建优先级队列对象
    var pQueue = new PriorityQueue();

    // 添加元素
    pQueue.enqueue("abc", 10);
    pQueue.enqueue("cba", 5);
    pQueue.enqueue("nba", 12);
    pQueue.enqueue("mba", 3);
    alert(pQueue);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值