Skip to content

Instantly share code, notes, and snippets.

@qwasfun

qwasfun/Queue.js Secret

Created January 4, 2025 12:19
Show Gist options
  • Select an option

  • Save qwasfun/d8041adb9a94dfe41c76d038857310e0 to your computer and use it in GitHub Desktop.

Select an option

Save qwasfun/d8041adb9a94dfe41c76d038857310e0 to your computer and use it in GitHub Desktop.
队列
class Queue {
constructor() {
this.head = 0; // 指向对头元素位置
this.tail = 0; // 指向队尾元素加 1 的位置
this.items = {};
}
// 向队列尾部添加一个(或多个)新的项
enqueue(item) {
this.items[this.tail] = item;
this.tail++;
}
// 移除队列的第一项,并返回被移除的元素
dequeue() {
if (this.isEmpty()) {
return undefined;
}
const result = this.items[this.head];
delete this.items[this.head];
this.head++;
return result;
}
// 查看队列头元素
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.head];
}
// 判断队列中是否为空
isEmpty() {
return this.head - this.tail === 0;
}
// 返回队列包含元素的个数
size() {
return this.tail - this.head;
}
// 清空队列
// 可以调用 dequeue 直到返回 undefined,
// 也可以直接将队列中的数学重置为初始值
clear() {
this.items = {};
this.head = 0;
this.tail = 0;
}
// 用字符串形式打印出队列中元素
toString() {
if (this.isEmpty()) {
return "";
}
let objectString = `${this.items[this.head]}`;
for (let i = this.head + 1; i < this.tail; i++) {
objectString = `${objectString},${this.items[i]}`;
}
return objectString;
}
}
let q = new Queue();
console.log(q.isEmpty()); // true
q.enqueue("Alice");
q.enqueue("Bob");
q.enqueue("Charles");
console.log(q.size()); // 3
console.log(q.toString()); // Alice,Bob,Charles
console.log(q.peek()); // Alice
console.log(q.isEmpty()); // false
q.dequeue(); // 移除 Alice
q.dequeue(); // 移除 Bob
console.log(q.toString()); // Charles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment