这是PriorityQueue类的完整实现-
class PriorityQueue { constructor(maxSize) { //设置默认的最大大小(如果未提供) if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; //初始化一个包含队列值的数组。 this.container = []; } //帮助程序功能在开发时显示所有值 display() { console.log(this.container); } //检查队列是否为空 isEmpty() { return this.container.length === 0; } //检查队列是否已满 isFull() { return this.container.length >= this.maxSize; } enqueue(data, priority) { //检查队列是否已满 if (this.isFull()) { console.log("队列溢出!"); return; } let currElem = new this.Element(data, priority); let addedFlag = false; //由于我们要添加元素以结束,因此我们将其推送。 for (let i = 0; i < this.container.length; i++) { if (currElem.priority < this.container[i].priority) { this.container.splice(i, 0, currElem); addedFlag = true; break; } } if (!addedFlag) { this.container.push(currElem); } } dequeue() { //检查是否为空 if (this.isEmpty()) { console.log("队列下溢!"); return; } return this.container.pop(); } peek() { if (isEmpty()) { console.log("队列下溢!"); return; } return this.container[this.container.length - 1]; } clear() { this.container = []; } } //创建一个内部类,用于在队列中创建新节点 //每个元素都有一些数据和优先级 PriorityQueue.prototype.Element = class { constructor(data, priority) { this.data = data; this.priority = priority; } };