使用 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