Created
November 9, 2018 17:47
-
-
Save anish000kumar/35c384f948274a723925571a20cd2f27 to your computer and use it in GitHub Desktop.
Get middle node of linked list
This file contains 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
function getListMiddle(head){ | |
let slow = head; | |
let fast = head; | |
let moveBoth = false; | |
// to get second element, in case of two mid-nodes, use 'fast' instead of 'fast.next' | |
while(fast.next){ | |
if(moveBoth){ | |
slow = slow.next; | |
fast = fast.next; | |
} | |
else{ | |
fast = fast.next; | |
} | |
moveBoth = !moveBoth; | |
} | |
return slow; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment