Skip to content

Commit 6855dce

Browse files
committed
--update : add doubly link list
1 parent c78f6ed commit 6855dce

File tree

1 file changed

+68
-0
lines changed
  • src/_DataStructures_/DoublyLinkedList

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/* eslint-disable class-methods-use-this */
2+
class Node {
3+
constructor(data, previous, next) {
4+
this.data = data;
5+
this.previous = previous;
6+
this.next = next;
7+
}
8+
}
9+
10+
class DoublyLinkedList {
11+
constructor() {
12+
// head -> tail
13+
// head <- tail
14+
this.head = new Node(null, null, null);
15+
this.tail = new Node(null, null, null);
16+
this.head.next = this.tail; // head next point to tail
17+
this.tail.previous = this.head; // tail previous point to head
18+
}
19+
20+
addAtBeginning(value) {
21+
const newNode = new Node(value, this.head, this.head.next);
22+
this.head.next.previous = newNode;
23+
this.head.next = newNode;
24+
}
25+
26+
addAtEnd(value) {
27+
const newNode = new Node(value, this.tail.previous, this.tail);
28+
this.tail.previous.next = newNode;
29+
this.tail.previous = newNode;
30+
}
31+
32+
removeAtBeginning() {
33+
this.remove(this.head.next);
34+
}
35+
36+
removeAtEnd() {
37+
this.remove(this.tail.previous);
38+
}
39+
40+
remove(node) {
41+
const previousNode = node.previous;
42+
const nextNode = node.next;
43+
previousNode.next = nextNode;
44+
nextNode.previous = previousNode;
45+
}
46+
47+
length() {
48+
let address = this.head.next;
49+
let count = 0;
50+
while (address !== this.tail) {
51+
count += 1;
52+
address = address.next;
53+
}
54+
return count;
55+
}
56+
57+
display() {
58+
let address = this.head.next;
59+
while (address !== this.tail) {
60+
console.log(address.data);
61+
address = address.next;
62+
}
63+
}
64+
}
65+
66+
module.exports = {
67+
DoublyLinkedList,
68+
};

0 commit comments

Comments
 (0)