forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.js
105 lines (90 loc) · 2.62 KB
/
DoublyLinkedList.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
class DoublyListNode {
constructor(value, previous, next) {
this.value = value;
this.next = next;
this.previous = previous;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToFront(value) {
let newNode = new DoublyListNode(value, null, this.head);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.head.previous = newNode;
this.head = newNode;
}
}
addToEnd(value) {
let newNode = new DoublyListNode(value, this.tail, null);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
remove(value) {
if (this.head === null) {
return;
}
if (this.head.value === value) {
this.head = this.head.next;
if (this.head !== null) {
this.head.previous = null;
}
} else if (this.tail.value === value) {
this.tail = this.tail.previous;
if (this.tail !== null) {
this.tail.next = null;
}
} else {
let currentNode = this.head;
let nodeToDelete = null;
while (currentNode.next !== null) {
if (currentNode.next.value === value) {
nodeToDelete = currentNode.next;
currentNode.next = currentNode.next.next;
if (currentNode.next !== null) {
currentNode.next.previous = currentNode;
}
break;
}
currentNode = currentNode.next;
}
if (nodeToDelete === null) {
console.log("Value not found");
}
}
}
readFromFront() {
if (this.head === null) {
console.log("Empty");
return;
}
let currentNode = this.head;
console.log("Reading from the Front");
while (currentNode !== null) {
console.log(currentNode.value);
currentNode = currentNode.next;
}
}
readFromEnd() {
if (this.head === null) {
console.log("Empty");
return;
}
let currentNode = this.tail;
console.log("Reading from the End");
while (currentNode !== null) {
console.log(currentNode.value);
currentNode = currentNode.previous;
}
}
}