Skip to content

Commit 2b7ea53

Browse files
authored
Merge pull request #3750 from Nickx58/patch-4
Create linked_list.js
2 parents d1cd34d + dd52e26 commit 2b7ea53

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class LinkedList {
2+
constructor(value) {
3+
this.head = null;
4+
this.length = 0;
5+
this.addToHead(value);
6+
}
7+
8+
addToHead(value) {
9+
const newNode = { value };
10+
newNode.next = this.head;
11+
this.head = newNode;
12+
this.length++;
13+
return this;
14+
}
15+
16+
removeFromHead() {
17+
if (this.length === 0) {
18+
return undefined;
19+
}
20+
21+
const value = this.head.value;
22+
this.head = this.head.next;
23+
this.length--;
24+
25+
return value;
26+
}
27+
28+
find(val) {
29+
let thisNode = this.head;
30+
31+
while(thisNode) {
32+
if(thisNode.value === val) {
33+
return thisNode;
34+
}
35+
36+
thisNode = thisNode.next;
37+
}
38+
39+
return thisNode;
40+
}
41+
42+
remove(val) {
43+
if(this.length === 0) {
44+
return undefined;
45+
}
46+
47+
if (this.head.value === val) {
48+
return this.removeFromHead();
49+
}
50+
51+
let previousNode = this.head;
52+
let thisNode = previousNode.next;
53+
54+
while(thisNode) {
55+
if(thisNode.value === val) {
56+
break;
57+
}
58+
59+
previousNode = thisNode;
60+
thisNode = thisNode.next;
61+
}
62+
63+
if (thisNode === null) {
64+
return undefined;
65+
}
66+
67+
previousNode.next = thisNode.next;
68+
this.length--;
69+
return this;
70+
}
71+
}

0 commit comments

Comments
 (0)