DoublyLinkedList.js
1.97 KB
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
"use strict";
/**
* A Doubly Linked List, because there aren't enough in the world...
* this is pretty much a direct JS port of the one wikipedia
* https://en.wikipedia.org/wiki/Doubly_linked_list
*
* For most usage 'insertBeginning' and 'insertEnd' should be enough
*
* nodes are expected to something like a POJSO like
* {
* prev: null,
* next: null,
* something: 'whatever you like'
* }
*/
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
insertBeginning(node) {
if (this.head === null) {
this.head = node;
this.tail = node;
node.prev = null;
node.next = null;
this.length++;
} else {
this.insertBefore(this.head, node);
}
}
insertEnd(node) {
if (this.tail === null) {
this.insertBeginning(node);
} else {
this.insertAfter(this.tail, node);
}
}
insertAfter(node, newNode) {
newNode.prev = node;
newNode.next = node.next;
if (node.next === null) {
this.tail = newNode;
} else {
node.next.prev = newNode;
}
node.next = newNode;
this.length++;
}
insertBefore(node, newNode) {
newNode.prev = node.prev;
newNode.next = node;
if (node.prev === null) {
this.head = newNode;
} else {
node.prev.next = newNode;
}
node.prev = newNode;
this.length++;
}
remove(node) {
if (node.prev === null) {
this.head = node.next;
} else {
node.prev.next = node.next;
}
if (node.next === null) {
this.tail = node.prev;
} else {
node.next.prev = node.prev;
}
node.prev = null;
node.next = null;
this.length--;
}
// FIXME: this should not live here and has become a dumping ground...
static createNode(data) {
return {
prev: null,
next: null,
data: data
};
}
}
module.exports = DoublyLinkedList;