Skip to content

Commit 6a95577

Browse files
committed
Implement doubly linked list
1 parent e6cb227 commit 6a95577

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

Diff for: linked-list-double.js

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.prev = null;
5+
this.next = null;
6+
}
7+
}
8+
9+
class DoublyLinkedList {
10+
constructor() {
11+
this.head = null;
12+
this.tail = null;
13+
this.size = 0;
14+
}
15+
16+
isEmpty() {
17+
return this.size === 0;
18+
}
19+
20+
getSize() {
21+
return this.size;
22+
}
23+
24+
prepend(value) {
25+
const node = new Node(value);
26+
if (this.isEmpty()) {
27+
this.head = node;
28+
this.tail = node;
29+
} else {
30+
node.next = this.head;
31+
this.head.prev = node;
32+
this.head = node;
33+
}
34+
this.size++;
35+
}
36+
37+
append(value) {
38+
const node = new Node(value);
39+
if (this.isEmpty()) {
40+
this.head = node;
41+
this.tail = node;
42+
} else {
43+
this.tail.next = node;
44+
node.prev = this.tail;
45+
this.tail = node;
46+
}
47+
this.size++;
48+
}
49+
50+
removeFromFront() {
51+
if (this.isEmpty()) {
52+
return null;
53+
}
54+
const value = this.head.value;
55+
this.head = this.head.next;
56+
this.size--;
57+
return value;
58+
}
59+
60+
removeFromEnd() {
61+
if (this.isEmpty()) {
62+
return null;
63+
}
64+
const value = this.tail.value;
65+
if (this.size === 1) {
66+
this.head = null;
67+
this.tail = null;
68+
} else {
69+
this.tail = this.tail.prev;
70+
this.tail.next = null;
71+
}
72+
this.size--;
73+
return value;
74+
}
75+
76+
print() {
77+
if (this.isEmpty()) {
78+
console.log("List is empty");
79+
} else {
80+
let curr = this.head;
81+
let list = "";
82+
while (curr) {
83+
list += `${curr.value}<->`;
84+
curr = curr.next;
85+
}
86+
console.log(list);
87+
}
88+
}
89+
}
90+
91+
const list = new DoublyLinkedList();
92+
list.append(1);
93+
list.append(2);
94+
list.append(3);
95+
list.prepend(0);
96+
list.print();
97+
list.removeFromEnd();
98+
list.print();
99+
list.removeFromFront();
100+
list.print();

0 commit comments

Comments
 (0)