-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list.ts
98 lines (79 loc) · 2.01 KB
/
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/** Linked list. */
export class LinkedList<T> {
public value: T | null = null;
/** List of nodes. */
public tail: LinkedList<T> | null = null;
public constructor(value?: T) {
if (value !== undefined && value !== null) {
this.value = value;
}
}
public static fromArray<T>(values: readonly T[]): LinkedList<T> {
const list = new LinkedList<T>();
values.forEach(value => list.add(value));
return list;
}
protected removeNode(): void {
this.value = this.tail?.value ?? null;
this.tail = this.tail?.tail ?? null;
}
/**
* Adds a value to the end of the list.
* @param value Value.
*
* @example
* const list = new LinkedList(1);
* list.add(2).add(3).add(4); // 1 -> 2 -> 3 -> 4.
*/
public add(value: T): LinkedList<T> {
let current: LinkedList<T> = this;
while (current.tail !== null) {
current = current.tail;
}
if (current.value === null) {
current.value = value;
} else {
current.tail = new LinkedList(value);
}
return this;
}
/**
* Removes all values from the list.
* @param value Value to be remove.
*
* @example
* const list = new LinkedList(2);
* list.add(1).add(2).add(2).add(3); // 2 -> 1 -> 2 -> 2 -> 3.
* list.remove(2); // 1 -> 3.
*/
public remove(value: T): LinkedList<T> {
let current: LinkedList<T> | null = this;
while (current !== null) {
if (current.value === value) {
current.removeNode();
} else {
current = current.tail;
}
}
return this;
}
/**
* Converts a linked list to an array.
* If the list is cyclic, an infinite loop will occur.
*
* @example
* const list = new LinkedList(1);
* list.add(2).add(3).add(4);
*
* list.toArray(); // [1, 2, 3, 4].
*/
public toArray(): (T | null)[] {
let array: (T | null)[] = [];
let current: LinkedList<T> | null = this;
while (current !== null) {
array.push(current.value)
current = current.tail
}
return array;
}
}