1. 程式人生 > 實用技巧 >js-資料結構-佇列

js-資料結構-佇列

佇列是遵循先進先出的一種資料結構,在尾部新增新元素,並從頂部移除元素。

1.普通佇列

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());
    }
};

2.優先佇列:元素的新增基於優先順序

//繼承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){
            this.items.splice(i,0,queueElement);            
            added = true;
            break;
        }
    }
    if (!added){
        this.items.push(queueElement);
    }
};
PriorityQueue.prototype.print=function () {
    for(let i=0;i<this.items.length;i++){
        console.log(`${this.items[i].element}  - ${this.items[i].priority}`);
    }
};

3.迴圈佇列(擊鼓傳花模擬)

function hotPotato (nameList, num){
 
    let queue = new Queue();
 
    for (let i=0; i<nameList.length; i++){
        queue.enqueue(nameList[i]); //所有名單加入佇列
    }
 
    let eliminated = '';
    while (queue.size() > 1){
        for (let i=0; i<num; i++){
            queue.enqueue(queue.dequeue()); //從佇列開頭移除一項,再將其新增到佇列末尾
        }
        eliminated = queue.dequeue();   //一旦傳遞次數到達指定的數字,拿著花的人就被淘汰了(從佇列中移除)
        console.log(eliminated + ' was eliminated from the Hot Potato game.');
    }
 
    return queue.dequeue(); //最後剩下的人是勝者
}
 
let names = ['John','Jack','Camila','Ingrid','Carl'];
let winner = hotPotato(names, 7);
console.log('The winner is: ' + winner);