File tree 2 files changed +36
-2
lines changed
src/_DataStructures_/LinkedList
2 files changed +36
-2
lines changed Original file line number Diff line number Diff line change @@ -168,5 +168,26 @@ describe('Data Structures: Linked Lists', () => {
168
168
expect ( list . getFirst ( ) . data ) . toEqual ( 15 ) ;
169
169
} ) ;
170
170
} ) ;
171
+
172
+ describe ( 'getAt(index)' , ( ) => {
173
+ beforeEach ( ( ) => {
174
+ list . addAtBeginning ( 'Hello' ) ;
175
+ list . addAtEnd ( 'There!' ) ;
176
+ list . addAtEnd ( 'Welcome' ) ;
177
+ } ) ;
178
+
179
+ it ( 'Should return `null` for empty list regardless of index value' , ( ) => {
180
+ list . delete ( ) ;
181
+ expect ( list . getAt ( 10 ) ) . toEqual ( null ) ;
182
+ } ) ;
183
+
184
+ it ( 'Should return the node for given index' , ( ) => {
185
+ expect ( list . getAt ( 1 ) . data ) . toEqual ( 'There!' ) ;
186
+ } ) ;
187
+
188
+ it ( 'Should return the last element for large index' , ( ) => {
189
+ expect ( list . getAt ( 10 ) . data ) . toEqual ( 'Welcome' ) ;
190
+ } ) ;
191
+ } ) ;
171
192
} ) ;
172
193
} ) ;
Original file line number Diff line number Diff line change @@ -21,11 +21,9 @@ class LinkedList {
21
21
this . head = node ;
22
22
} else {
23
23
let address = this . head ;
24
-
25
24
while ( address . next ) {
26
25
address = address . next ;
27
26
}
28
-
29
27
address . next = node ;
30
28
}
31
29
}
@@ -71,6 +69,21 @@ class LinkedList {
71
69
return address ;
72
70
}
73
71
72
+ getAt ( index ) {
73
+ if ( ! this . length ( ) ) {
74
+ return null ;
75
+ }
76
+ let address = this . head ;
77
+ let count = index ;
78
+
79
+ while ( count && address . next ) {
80
+ address = address . next ;
81
+ count -= 1 ;
82
+ }
83
+
84
+ return address ;
85
+ }
86
+
74
87
length ( ) {
75
88
let address = this . head ;
76
89
let count = 0 ;
You can’t perform that action at this time.
0 commit comments