-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
106 lines (97 loc) · 2.17 KB
/
index.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
class Node {
constructor(data) {
this.data = data;
this.previous = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.numberOfValues = 0;
}
add(data) {
const node = new Node(data);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
node.previous = this.tail;
this.tail.next = node;
this.tail = node;
}
this.numberOfValues++;
}
remove(data) {
let current = this.head;
while (current) {
if (current.data === data) {
if (current === this.head && current === this.tail) {
this.head = null;
this.tail = null;
} else if (current === this.head) {
this.head = this.head.next;
this.head.previous = null;
} else if (current === this.tail) {
this.tail = this.tail.previous;
this.tail.next = null;
} else {
current.previous.next = current.next;
current.next.previous = current.previous;
}
this.numberOfValues--;
}
current = current.next;
}
}
insertAfter(data, toNodeData) {
let current = this.head;
while (current) {
if (current.data === toNodeData) {
var node = new Node(data);
if (current === this.tail) {
this.add(data);
} else {
current.next.previous = node;
node.previous = current;
node.next = current.next;
current.next = node;
this.numberOfValues++;
}
}
current = current.next;
}
}
traverse(fn) {
let current = this.head;
while (current) {
if (fn) {
fn(current);
}
current = current.next;
}
}
traverseReverse(fn) {
let current = this.tail;
while (current) {
if (fn) {
fn(current);
}
current = current.previous;
}
}
length() {
return this.numberOfValues;
}
print() {
let string = '';
let current = this.head;
while (current) {
string += current.data + ' ';
current = current.next;
}
return string.trim();
}
}
module.exports = DoublyLinkedList;