-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.ts
77 lines (49 loc) · 1.06 KB
/
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
type Node<T> = {
next?: Node<T>;
value: T
}
export class Queue<T> {
public length: number;
private tail?: Node<T>;
private head?: Node<T>;
constructor() {
this.length = 0;
this.tail = undefined;
this.head = undefined;
}
dequeue() {
if(!this.head) {
return undefined;
}
this.length--;
const head = this.head;
this.head = this.head.next;
head.next = undefined;
return head.value;
}
enqueue(item: T) {
const node = {value: item} as Node<T>;
this.length ++;
if(!this.tail) {
this.head = node;
this.tail = this.head;
}
this.tail.next = node;
this.tail = node;
}
peak() {
if(!this.head) {
return undefined;
}
return this.head?.value;
}
}
const x = new Queue<number>;
x.enqueue(1);
console.log(x);
x.enqueue(2);
x.enqueue(3);
console.log(x.peak);
x.dequeue();
console.log(x);
console.log(x.peak());