-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFIFOQueue.ts
57 lines (47 loc) · 886 Bytes
/
FIFOQueue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
type Node<T> = {
value: T;
next: Node<T> | null;
};
export class FIFOQueue<T> {
private head: Node<T> | null = null;
private tail: Node<T> | null = null;
private size = 0;
constructor() {
this.clear();
}
enqueue(value: T) {
const node = { value, next: null };
if (this.head) {
this.tail!.next = node;
this.tail = node;
} else {
this.head = node;
this.tail = node;
}
this.size++;
}
dequeue() {
const current = this.head;
if (!current) {
return;
}
this.head = this.head!.next;
this.size--;
return current.value;
}
clear() {
this.head = null;
this.tail = null;
this.size = 0;
}
getSize() {
return this.size;
}
*[Symbol.iterator]() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
}