-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathdoublyLinkedList.js
More file actions
136 lines (108 loc) · 2.71 KB
/
doublyLinkedList.js
File metadata and controls
136 lines (108 loc) · 2.71 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
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
130
131
132
133
134
135
136
class Node {
constructor(value, prev = null, next = null) {
this.value = value;
this.next = next;
this.prev = prev;
}
}
const INSERT_POSITION = ['before', 'after'];
const TRAVERSE_DIRECTION = ['forward', 'backward'];
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
includes(value) {
if (this.head === null) {
return false;
}
let current = this.head;
while (current) {
if (current.value === value) {
return true;
}
current = current.next;
}
return false;
}
get(value) {
if (this.head === null) {
return null;
}
let current = this.head;
while (current) {
if (current.value === value) {
return current;
}
current = current.next;
}
return null;
}
append(value) {
const node = new Node(value, this.tail);
if (this.head === null) {
this.head = node;
this.tail = node;
return this;
}
this.tail.next = node;
this.tail = node;
return this;
}
// value1 = new value to insert
// value2 = anchor value in the list to which the new value is to be added
// position (before/after) = position relative to value2 to which value1 will be added
insert(value1, value2, position = 'after') {
if(!this.includes(value2) || !INSERT_POSITION.includes(position) || value2 == null) {
return this;
}
const newNode = new Node(value1);
const anchorNode = this.get(value2);
if(position === 'after') {
if(anchorNode === this.tail) {
this.tail = newNode;
}
newNode.next = anchorNode.next;
newNode.prev = anchorNode;
anchorNode.next = newNode;
} else {
if(anchorNode === this.head) {
this.head = newNode;
}
newNode.prev = anchorNode.prev;
(anchorNode.prev || {}).next = newNode;
anchorNode.prev = newNode;
newNode.next = anchorNode;
}
return this;
}
remove(value) {
if(!this.includes(value)) {
return false;
}
const node = this.get(value);
if(this.head === node) {
this.head = node.next;
}
if(this.tail === node) {
this.tail = node.prev;
}
(node.prev || {}).next = node.next;
(node.next || {}).prev = node.prev;
return true;
}
toString(direction = 'forward') {
if (this.head === null || !TRAVERSE_DIRECTION.includes(direction)) {
return '';
}
const key = direction === 'forward' ? 'next' : 'prev';
const arr = [];
let current = direction === 'forward' ? this.head : this.tail;
while (current) {
arr.push(current.value);
current = current[key];
}
return arr.join(', ');
}
}
module.exports = DoublyLinkedList;