JS数据结构及算法(二) 队列

队列是遵循先进先出的一种数据结构,在尾部添加新元素,并从顶部移除元素。

function Queue() {
    this.items = [];
}

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

优先队列:元素的添加基于优先级

//继承Queue
function PriorityQueue() {
    Queue.call(this);
}
PriorityQueue.prototype = Object.create(Queue.prototype);
PriorityQueue.prototype.constructor = PriorityQueue;
PriorityQueue.prototype.enqueue = function (element,priority) {
    function QueueElement (element, priority){
        this.element = element;
        this.priority = priority;
    }
    let queueElement = new QueueElement(element, priority);

    let added = false;
    for (let i=0; i<this.items.length; i++){
        if (queueElement.priority < this.items[i].priority){ // {2}
            this.items.splice(i,0,queueElement);             // {3}
            added = true;
            break; // {4}
        }
    }
    if (!added){
        this.items.push(queueElement); //{5}
    }
};
PriorityQueue.prototype.print=function () {
    for(let i=0;i<this.items.length;i++){
        console.log(`${this.items[i].element}  - ${this.items[i].priority}`);
    }
};

猜你喜欢

转载自www.cnblogs.com/jingmi-coding/p/9284824.html