-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.js
129 lines (106 loc) · 2.98 KB
/
list.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
export class ListNode {
list;
/** @type {ListNode<T>|null} */
previous;
/** @type {ListNode<T>|null} */
next = null;
/** @type {T} */
value;
/**
* @template T
*
* @param {List<T>} list
* @param {T} value
* @param {ListNode<T>|null} previous
*/
constructor(list, value, previous) {
this.list = list;
this.value = value;
this.previous = previous;
}
dispose() {
this.list = null;
this.value = null;
this.next = null;
this.previous = null;
}
}
export class List {
size;
/** @type {ListNode<T>|null} */
first = null;
/** @type {ListNode<T>|null} */
last = null;
/**
* @template T
* @param {T[]} array
*/
constructor(array) {
this.size = array.length;
if (this.size === 0) return;
this.first = new ListNode(this, array[0], null);
let current = this.first;
for (let i = 1; i < array.length; i++) {
current.next = new ListNode(this, array[i], current);
current = current.next;
}
this.last = current;
}
/**
* @param {ListNode<T>} node
*/
remove(node) {
this.#throwIfNodeInvalid(node);
if (node.previous === null) this.first = node.next;
else node.previous.next = node.next;
if (node.next === null) this.last = node.previous;
else node.next.previous = node.previous;
this.size -= 1;
node.dispose();
}
/**
* @param {T} value
* @param {ListNode<T>|null} node
*/
add(value, node) {
if (this.first === null && node === null) throw new Error("For not-empty list node should be specified");
this.#throwIfNodeInvalid(node);
const newNode = new ListNode(this, value, node);
if (this.first === null) {
this.first = newNode
} else {
newNode.next = node.next;
newNode.previous = node;
if (node.next !== null) node.next.previous = newNode;
node.next = newNode;
}
if (newNode.next === null) this.last = newNode;
}
/**
* @param {ListNode<T>} node
* @return {ListNode<T>}
*/
next(node) {
this.#throwIfNodeInvalid(node);
return node.next ?? this.first;
}
/**
* @param {ListNode<T>} node
* @return {ListNode<T>}
*/
previous(node) {
this.#throwIfNodeInvalid(node);
return node.previous ?? this.last;
}
* [Symbol.iterator]() {
let current = this.first;
while (current !== null) {
yield current;
current = current.next;
}
}
#throwIfNodeInvalid(node) {
if (node === null) throw new Error("Node can't be null");
if (node.list !== this) throw new Error("Node from different list");
}
}