-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.js
105 lines (96 loc) · 2.29 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
const Node = require('./Node');
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
addToHead(data) {
const newHead = new Node(data);
const currentHead = this.head;
if (currentHead) {
currentHead.setPreviousNode(newHead);
newHead.setNextNode(currentHead);
}
this.head = newHead;
if (!this.tail) {
this.tail = newHead;
}
}
addToTail(data) {
const newTail = new Node(data);
const currentTail = this.tail;
if (currentTail) {
currentTail.setNextNode(newTail);
newTail.setPreviousNode(currentTail);
}
this.tail = newTail;
if (!this.head) {
this.head = newTail;
}
}
removeHead() {
const removedHead = this.head;
if (!removedHead) {
return;
}
this.head = removedHead.getNextNode();
if (this.head) {
this.head.setPreviousNode(null);
}
if (removedHead === this.tail) {
this.removeTail();
}
return removedHead.data;
}
removeTail() {
const removedTail = this.tail;
if (!removedTail) {
return;
}
this.tail = removedTail.getPreviousNode();
if (this.tail) {
this.tail.setNextNode(null);
}
if (removedTail === this.head) {
this.removeHead();
}
return removedTail.data;
}
removeByData(data) {
let nodeToRemove;
let currentNode = this.head;
while (currentNode !== null) {
if (currentNode.data === data) {
nodeToRemove = currentNode;
break;
}
currentNode = currentNode.getNextNode();
}
if (!nodeToRemove) {
return null;
}
if (nodeToRemove === this.head) {
this.removeHead();
} else if (nodeToRemove === this.tail) {
this.removeTail();
} else {
const nextNode = nodeToRemove.getNextNode();
const previousNode = nodeToRemove.getPreviousNode();
nextNode.setPreviousNode(previousNode);
previousNode.setNextNode(nextNode);
}
return nodeToRemove;
}
printList() {
let currentNode = this.head;
let output = '<head> ';
while (currentNode !== null) {
output += currentNode.data + ' ';
currentNode = currentNode.getNextNode();
}
output += '<tail>';
console.log(output);
}
}
const subway = new DoublyLinkedList()
module.exports = DoublyLinkedList;