js(JavaScript)数据结构之队列(Queue)
在JavaScript中,队列是一种线性数据结构,遵循先进先出(FIFO)原则。以下是实现一个简单队列数据结构的示例代码:
class Queue {
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
enqueue(element) {
this.items[this.count] = element;
this.count++;
}
dequeue() {
if (this.isEmpty()) {
return undefined;
}
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return result;
}
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.lowestCount];
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.count - this.lowestCount;
}
clear() {
this.items = {};
this.count = 0;
this.lowestCount = 0;
}
toString() {
if (this.isEmpty()) {
return '';
}
let objString = `${this.items[this.lowestCount]}`;
for (let i = this.lowestCount + 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
// 使用示例
const queue = new Queue();
queue.enqueue('John');
queue.enqueue('Jack');
queue.enqueue('Camila');
console.log(queue.toString()); // 输出: John,Jack,Camila
console.log(queue.dequeue()); // 输出: John
console.log(queue.peek()); // 输出: Jack
这段代码定义了一个队列类Queue
,它包含了入队(enqueue
)、出队(dequeue
)、查看队首元素(peek
)、判断队列是否为空(isEmpty
)、获取队列大小(size
)、清空队列(clear
)以及将队列转换为字符串(toString
)的方法。这样,开发者可以通过这个类来实现和操作队列。
评论已关闭