File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
code/data_structures/src/linked_list Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments