-
-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy pathlinked-list.js
47 lines (41 loc) · 1.13 KB
/
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
var LinkedList = module.exports = function (value) {
this.value = value;
this.prev = this;
this.next = this;
};
LinkedList.prototype.appendNode = function (value) {
var node = new LinkedList(value);
node.prev = this;
node.next = this.next;
// Fix the linked list references
this.next = this.next.prev = node;
return node;
};
LinkedList.prototype.prependNode = function (value) {
var node = new LinkedList(value);
node.prev = this.prev;
node.next = this;
// Fix the linked list references
this.prev = this.prev.next = node;
return node;
};
LinkedList.prototype.removeNode = function () {
// Create a reference around the node to be removed
this.prev.next = this.next;
this.next.prev = this.prev;
// Remove existing references to the current list
this.next = this.prev = this;
return this;
};
LinkedList.prototype.containsNode = function (value) {
if (this.value === value) { return true; }
var node = this.next;
// Loop through the connections until we hit ourselves again
while (node !== this) {
if (node.value === value) {
return true;
}
node = node.next;
}
return false;
};