Skip to content

Commit 215fb21

Browse files
committed
add the at() method
1 parent 6f6fecc commit 215fb21

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/data-structures/linked-list/LinkedList.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,4 +309,24 @@ export default class LinkedList {
309309
// if the value dont exist:
310310
return -1;
311311
}
312+
313+
/**
314+
* Find the value of specified index.
315+
* @param {number} index
316+
* @returns {*}
317+
*/
318+
at(index) {
319+
// check if the index not exist
320+
if (index < 0 || index > this.getSize()) return undefined;
321+
let i = 0;
322+
let currNode = this.head;
323+
324+
// Iterate the list to find the index.
325+
while (i < index) {
326+
currNode = currNode.next;
327+
i++;
328+
}
329+
330+
return currNode.value;
331+
}
312332
}

0 commit comments

Comments
 (0)