使用 JavaScript 建立優先佇列
我們的類將具有以下功能:
- enqueue(element):用於向佇列中新增元素的功能。
- dequeue():從佇列中刪除元素的功能。
- peek():返回佇列前端的元素。
- isFull():檢查我們是否已達到佇列上的元素限制。
- isEmpty():檢查佇列是否為空。
- clear():刪除所有元素。
- display():顯示陣列的所有內容
讓我們從定義一個簡單的類開始,該類帶有一個建構函式,該建構函式獲取佇列的最大大小,以及一個輔助函式,該函式將在我們實現此類的其他函式時提供幫助。我們還必須將另一個結構定義為 PriorityQueue 類原型的部分,該結構將具有每個節點的優先順序和資料。正如我們實現堆疊一樣,我們也將使用陣列實現優先佇列。
示例
class PriorityQueue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
// Init an array that'll contain the queue values.
this.container = [];
}
// Helper function to display all values while developing
display() {
console.log(this.container);
}
// Checks if queue is empty
isEmpty() {
return this.container.length === 0;
}
// checks if queue is full
isFull() {
return this.container.length >= this.maxSize;
}
}
// Create an inner class that we'll use to create new nodes in the queue
// Each element has some data and a priority
PriorityQueue.prototype.Element = class {
constructor (data, priority) {
this.data = data; this.priority = priority;
}
}我們還定義了另外兩個函式 isFull 和 isEmpty,用於檢查堆疊是否已滿或為空。
isFull 函式只是檢查容器的長度是否等於或大於 maxSize,並相應地返回。
isEmpty 函式檢查容器的大小是否為 0。
這些在定義其他操作時將很有用。從現在開始,我們定義的函式都將進入 PriorityQueue 類。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP