-
Notifications
You must be signed in to change notification settings - Fork 2
/
DoubleLinkedList.js
78 lines (72 loc) · 2.12 KB
/
DoubleLinkedList.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
// Double LinkedList
let Node = function (data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
let DoublyLinkedList = function () {
this.head = null;
this.tail = null;
this.length = 0;
this.add = function (data) {
let node = new Node(data);
if (this.head === null) {
this.head = node;
this.length++;
return;
}
let currentNode = this.head;
let previousNode;
while (currentNode.next !== null) {
previousNode = currentNode;
currentNode = currentNode.next;
}
this.tail = node;
currentNode.next = node;
node.prev = currentNode;
this.length++;
return;
};
this.remove = function (e) {
if (this.head === null) {
return null;
} else {
if (this.head.data === e) {
this.head = this.head.next;
this.head.prev = null;
return;
} else if (this.tail.data === e) {
this.tail = this.tail.prev;
this.tail.next = null;
return;
} else {
let currentNode = this.head;
let prevNode;
while (currentNode && currentNode.data !== e) {
prevNode = currentNode;
currentNode = currentNode.next;
}
if (!currentNode) {
return null;
} else {
let nextNode = currentNode.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
return;
}
}
}
};
this.reverse = function () {
if (!this.head) {
return null;
} else {
let currentNode = this.head;
while (currentNode) {
[currentNode.prev, currentNode.next] = [currentNode.next, currentNode.prev];
currentNode = currentNode.prev;
}
[this.head, this.tail] = [this.tail, this.head];
}
};
};