- 定義
隊列是遵循FIFO(First In First Out,先進先出)原則的一組有序的項。
在現實中,最常見的隊列的例子就是排隊:
來自《javascript數據結構與算法》
- 創建隊列
- 聲明類并聲明一個數組用于存儲隊列中元素的數據結構。
function Queue() {
var items = [];
//這里是屬性和方法
}
- 實現enqueue()方法,向隊列尾部添加數個新的項。
this.enqueue = function(element) {
//用push方法,將元素添加到數組末尾
items.push(element);
};
- 實現dequeue()方法,移除隊的第一項(隊首),并返回被移除的元素。
this.dequeue = function() {
//shift方法,移除數組中的第一項(索引為0)的元素
return items.shift();
};
- front()方法,返回隊列中的第一個元素,不改變隊列。
this.front = function() {
return items.shift();
};
- isEmpty()方法,如果隊列中不包含任何元素,返回true,否則返回false。
this.isEmpty = function() {
return items.length == 0;
};
- clear()方法,清空隊列元素
this.clear = function() {
items = [];
};
- size()方法,返回隊列包含的元素個數。
this.size = function(){
return items.lenght;
};
- 完整代碼如下
function Queue() {
var items = [];
this.enqueue = function(element) {
items.push(element);
};
this.dequeue = function() {
return items.shift();
};
this.front = function() {
return items[0];
};
this.isEmpty = function() {
return items.length == 0;
};
this.clear = function() {
items = [];
};
this.size = function() {
return items.length;
};
this.print = function() {
console.log(items.toString());
}
}
var queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
queue.print(); // "1,2"
- 優先隊列
現實生活中也有優先隊列,如頭等艙>商務艙>經濟艙,接下來我們用代碼實現下優先隊列。
function PriorityQueue() {
//聲明一個items用于保存元素
var items = [];
//創建一個QueueElement類,用于保存元素和其在隊列中的優先級(priority越小,優先級越高)
function QueueElement(element,priority) {
this.element = element;
this.priority = priority;
}
this.enqueue = function(element,priority) {
var queueElement = new QueueElement(element,priority);
//如果隊列為空,可以將元素入列
if(this.isEmpty()) {
items.push(queueElement);
}else {
var added = false;
//反之就循環隊列里面的每一個元素,比較優先級,如果priority小(優先級越高)的話,就用splice()方法放在該元素的前面
for(var i=0; i<items.length; i++) {
if(queueElement.priority < items[i].priority) {
items.splice(i,0,queueElement);
added = true;
break;
}
}
//如果添加的元素的priority比隊列中的每一個元素都要大的話,就把它添加到隊列的最后面
if(!added) {
items.push(queueElement);
}
}
};
this.isEmpty = function() {
return items.length === 0;
};
this.print = function() {
console.log(items);
};
}
var priorityQueue = new PriorityQueue();
priorityQueue.enqueue("one",1);
priorityQueue.enqueue("two",2);
priorityQueue.enqueue("zero",0);
priorityQueue.enqueue("four",4);
priorityQueue.print(); // "0,1,2,4"
- 循環隊列
循環隊列的一個例子就是擊鼓傳花游戲(HotPotato)。在這個游戲中,孩子們圍成一個圓圈,把花盡快地傳遞給旁邊的人。某一時刻傳花停止,這個時候花在誰手里,誰就退出圓圈結束游戲。重復這個過程,直到只剩一個孩子(勝者)。
function hotPotato(nameList,num) {
var queue = new Queue();
//將傳入的nameList遍歷,將每一項添加到隊列中
for(var i=0; i<nameList; i++) {
queue.enqueue(nameList[i]);
}
var eliminated = '';
//如果隊列里的size大于1,就一直循環下去
while(queue.size() > 1) {
//將第一項放到最后一項,循環給定的num
for(var i=0; i<num; i++) {
queue.enqueue(queue.dequeue);
}
//傳遞次數達到了給定的數值,(移除第一項)
eliminated = queue.dequeue();
console.log(eliminated + '淘汰');
}
//返回隊列中僅有的最后一項
return queue.dequeue();
}
var names = ['a','b','c','d','e'];
var winner = hotPotato(names,7);
console.log('勝利者' + winner);
參考學習 :
《javascript數據結構與算法學習》
《數據結構與算法javascript描述》