Skip to content

Instantly share code, notes, and snippets.

@anish000kumar
Created November 9, 2018 17:47
Show Gist options
  • Save anish000kumar/35c384f948274a723925571a20cd2f27 to your computer and use it in GitHub Desktop.
Save anish000kumar/35c384f948274a723925571a20cd2f27 to your computer and use it in GitHub Desktop.
Get middle node of linked list
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