js优先队列的定义和使用

//队列,先入先出,FIFO
function Queue() {
    this.items = [];
}

Queue.prototype = {
    constructor: Queue,
    enqueue: function(elements) {
        this.items.push(elements);
    },
    dequeue: function() {
        return this.items.shift();
    },
    front: function() {
        return this.items[0];
    },
    size: function() {
        return this.items.length;
    },
    isEmpty: function() {
        return this.items.length == 0;
    },
    clear: function() {
        this.items = [];
    },
    print: function() {
        console.log(this.items.toString());
    }
}

//队列的基本使用
// var queue = new Queue();
// console.log(queue.isEmpty());
// queue.enqueue('huang');
// console.log(queue.size);

//优先队列的定义 这里使用组合继承的方式继承自Queue队列
function PriorityQueue() {
    Queue.call(this);
};

PriorityQueue.prototype = new Queue();
PriorityQueue.prototype.constructer = PriorityQueue;
PriorityQueue.prototype.enqueue = function(element, priority) {
    function QueueElement(tempelement, temppriority) {
        this.element = tempelement;
        this.priority = temppriority;
    }
    var queueElement = new QueueElement(element, priority);

    if (this.isEmpty()) {
        this.items.push(queueElement);
    } else {
        var added = false;
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].priority > queueElement.priority) {
                this.items.splice(i, 0, queueElement);
                added = true;
                break;
            }
        }
        if (!added) {
            this.items.push(queueElement);
        }
    }
}
//这个方法可以用Queue的默认实现
PriorityQueue.prototype.print=function(){
    var result='';
    for(var i = 0; i < this.items.length;i++){
        result += JSON.stringify(this.items[i]);
      }
      return result;
}

 优先队列的使用

var priorityQueue = new PriorityQueue();
    priorityQueue.enqueue("cheng", 2);
    priorityQueue.enqueue("du", 3);
    priorityQueue.enqueue("huang", 1);
    console.log(priorityQueue.print());//{"element":"huang","priority":1}{"element":"cheng","priority":2}{"element":"du","priority":3}
    console.log(priorityQueue.size());//3
    console.log(priorityQueue.dequeue());//{ element="huang",  priority=1}
    console.log(priorityQueue.size());//2

 

转载于:https://www.cnblogs.com/greatluoluo/p/6306779.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值