Skip to content

Commit b3895a4

Browse files
committed
Data structures: implement doubly linked list - insert and remove at K index
1 parent 8f2999c commit b3895a4

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
* Doubly Linked List implement with JavaScript
3+
*/
4+
5+
// Initialize a node
6+
7+
class Node {
8+
constructor(data, prev = null, next = null) {
9+
this.data = data;
10+
this.prev = prev;
11+
this.next = next;
12+
}
13+
}
14+
15+
class DoublyLinkedList {
16+
constructor() {
17+
this.head = null;
18+
this.tail = null;
19+
this.size = 0;
20+
}
21+
22+
// Search first node with key K
23+
searchFirstNode(data) {
24+
if (!this.head) return null;
25+
let current = this.head;
26+
while (current !== null && current.data !== data) {
27+
current = current.next;
28+
}
29+
30+
return current;
31+
}
32+
33+
// Insert Node at index
34+
insert(data, index) {
35+
// If index is out of range
36+
if (index > 0 && index > this.size) return;
37+
let node = new Node(data);
38+
39+
// If index = 0: insert at head
40+
if (index === 0) {
41+
if (!this.head) {
42+
this.head = node;
43+
this.tail = node;
44+
this.size++;
45+
} else {
46+
let current = this.head;
47+
node.next = current;
48+
current.prev = node;
49+
this.head = node;
50+
this.size++;
51+
}
52+
} else if (index === this.size) {
53+
let current = this.tail;
54+
node.prev = current;
55+
current.next = node;
56+
this.tail = node;
57+
this.size++;
58+
} else {
59+
// Insert at given index k
60+
let counter = 0;
61+
let current = this.head;
62+
while (counter < index) {
63+
current = current.next;
64+
counter++;
65+
}
66+
node.next = current;
67+
current.prev.next = node;
68+
node.prev = current.prev;
69+
this.size++;
70+
}
71+
}
72+
73+
// Remove a node at given K index
74+
remove(index) {
75+
if (index > 0 && index > this.size) return;
76+
77+
// index = 0: Remove the head node
78+
if (index === 0) {
79+
if (!this.head) return;
80+
else {
81+
this.head = this.head.next;
82+
this.head.prev = null;
83+
this.size--;
84+
}
85+
} else if (index === this.size - 1) {
86+
this.tail = this.tail.prev;
87+
this.tail.next = null;
88+
this.size--;
89+
} else {
90+
let counter = 0;
91+
let current = this.head;
92+
while (counter < index) {
93+
current = current.next;
94+
counter++;
95+
}
96+
current.prev.next = current.next;
97+
current.next.prev = current.prev;
98+
this.size--;
99+
}
100+
}
101+
}
102+
103+
const dbl = new DoublyLinkedList();
104+
105+
dbl.insert(100, 0);
106+
dbl.insert(200, 0);
107+
dbl.insert(400, 0);
108+
dbl.insert(300, 1);
109+
dbl.insert(500, 3);
110+
dbl.remove(1);
111+
112+
console.log(dbl);

0 commit comments

Comments
 (0)