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