JS基于数组的优先级队列实现与常用方法

function PriorityQueue() {
    // 创建内部类
    function Node(data,priority) {
        this.data = data;
        this.priority = priority;
    }

    // 封装属性
    this.items = [];

    // 实现插入方法
    PriorityQueue.prototype.enqueue = function(data,priority) {
        // 创建对象
        var node =  new Node(data,priority);

        // 如果队列没有元素 直接添加
        if(this.items.length == 0) {
            this.items.push(node);
        }
        else {
            var added = false;      // 判断是否已经添加
            for(var  i = 0;  i < this.items.length; i++) {
                // 根据优先级查找应该插入哪里,优先级高的则插在前面
                if(priority >  this.items[i].priority ) {
                    added = true;
                    this.items.splice(i,0,node);
                    break;
                }
            }
            // 如果还没有添加 则直接添加将元素添加在后面
            if(!added) {
                this.items.push(node);
            }
        }
    }
    PriorityQueue.prototype.toString = function() {
        var str = "";
        for (const key in this.items) {
            if (this.items.hasOwnProperty(key)) {
                str +=  "<值:>"+this.items[key].data + ",优先级:"+this.items[key].priority+ "\n ";
            }
        }
        return str;
    }

    PriorityQueue.prototype.deQueue = function(){
        return this.items.shift();
    }

    PriorityQueue.prototype.front = function(){
        return this.items[0];
    }

    PriorityQueue.prototype.size = function(){
        return this.items.length;
    }   

    PriorityQueue.prototype.isEmpty=function() {
        return this.items.length==0;
    }

}

var pq = new PriorityQueue();
pq.enqueue(1,1);
pq.enqueue(1,2);
pq.enqueue(1,3);
pq.enqueue(1,4);
pq.enqueue(1,6);
pq.enqueue(1,5);

console.log(pq.size())

 

posted @ 2020-04-04 13:21  正义de键盘侠  阅读(304)  评论(0)    收藏  举报