-
Notifications
You must be signed in to change notification settings - Fork 0
/
double_linked_list.js
62 lines (52 loc) · 1.25 KB
/
double_linked_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
class DoubleLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
insert(data, index) {
if (index < 0) throw new Error('invalid index');
const newNode = new Node(data);
if (this.head === null && this.tail === null) {
this.head = newNode;
this.tail = newNode;
return;
}
if (index === 0) {
if (this.head.next === null) this.head = newNode;
else {
this.head.next.prev = newNode;
newNode.next = this.head.next;
this.head = newNode;
}
return;
}
let currentNode = this.head;
let previousNode = null;
let count = 0;
while (count < index) {
if (currentNode === null) throw new Error('index overflow');
previousNode = currentNode;
currentNode = currentNode.next;
count++;
}
newNode.prev = previousNode;
previousNode.next = newNode;
if (currentNode) newNode.next = currentNode.next;
else this.tail = newNode;
}
*traverse() {
if (this.head === null) return;
let currentNode = this.head;
while (currentNode) {
yield currentNode;
currentNode = currentNode.next;
}
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.prev = null;
}
}