Created
February 3, 2023 09:57
-
-
Save jordanrios94/322a6429df52612a436ddb28f9ebcc5f to your computer and use it in GitHub Desktop.
LinkedList Midpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Return the 'middle' node of a linked list. | |
- If the list has an even number of elements return the node at the end of the first half of the list. | |
- Do not use a counter variable | |
- Do not retrieve the size of the list | |
- Only iterate through the list one time | |
*/ | |
function midpoint(list) { | |
let slow = list.getFirst(); | |
let fast = list.getFirst(); | |
while (fast.next && fast.next.next) { | |
slow = slow.next; | |
fast = fast.next.next; | |
} | |
return slow; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment