-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.ts
53 lines (41 loc) · 962 Bytes
/
Queue.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
type Node<T> = {
value: T,
next?: Node<T>
}
export default class Queue<T> {
public length: number;
private head?: Node<T>;
private tail?: Node<T>;
constructor() {
this.head = this.tail = undefined;
this.length = 0;
}
enqueue(item: T): void {
const node = {value: item} as Node<T>;
this.length++;
if (!this.tail) {
this.tail = this.head = node;
return;
}
this.tail.next = node;
this.tail = node;
}
deque(): T | undefined {
if (!this.head) {
return undefined;
}
this.length--;
const head = this.head;
this.head = this.head.next;
// free
head.next = undefined;
// tail?
if (this.length === 0) {
this.tail = undefined;
}
return head.value;
}
peek(): T | undefined {
return this.head?.value;
}
}