-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list.ts
54 lines (45 loc) · 973 Bytes
/
linked-list.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
interface Node {
value: any;
next: Node;
}
export default class LinkedList {
private head: Node;
private length: number;
constructor() {
this.head = null;
this.length = 0;
}
get(position: number): any {
if (position >= this.length) {
throw new Error('Position out of list range');
}
let current = this.head;
for (let i = 0; i < position; i++) {
current = current.next;
}
return current;
}
add(value: any, position: number): void {
const node: Node = {
value,
next: null,
};
if (position == 0) {
this.head = node;
} else {
const prev = this.get(position - 1);
const next = prev.next;
prev.next = node;
node.next = next;
}
this.length++;
}
remove(position: number): void {
if (position == 0) {
this.head = this.head.next;
} else {
const prev = this.get(position - 1);
prev.next = prev.next.next;
}
}
}