-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinkedList.ts
77 lines (60 loc) · 1.34 KB
/
LinkedList.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
class Node<T> {
value: T;
next?: Node<T>;
constructor(value: T) {
this.value = value;
}
}
export class LinkedList<T> {
#head?: Node<T>;
#tail?: Node<T>;
#size = 0;
append(value: T): void {
const item = new Node(value);
if (this.#tail === undefined) {
this.#head = item;
this.#tail = item;
} else {
this.#tail.next = item;
this.#tail = item;
}
this.#size++;
}
prepend(value: T): void {
const item = new Node(value);
if (this.#head === undefined) {
this.#head = item;
this.#tail = item;
} else {
item.next = this.#head;
this.#head = item;
}
this.#size++;
}
removeAt(index: number): T | undefined {
if (this.#head == null || index < 0 || index >= this.#size) return;
let value: T;
if (index == 0) {
value = this.#head.value;
this.#head = this.#head.next;
this.#size--;
return value;
}
const prev = this.get(index - 1)!;
value = prev.next!.value;
prev.next = prev.next!.next;
this.#size--;
return value;
}
get(index: number): Node<T> | undefined {
if (index < 0 || index >= this.#size) return;
let current = this.#head;
for (let i = 0; i < index; i++) {
current = current!.next;
}
return current;
}
get size(): number {
return this.#size;
}
}