Last active
December 25, 2015 18:29
-
-
Save MLLeKander/7021349 to your computer and use it in GitHub Desktop.
findHead
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
Node findHead(Node start) { | |
int tortoiseSpeed = 0, hareSpeed = 0; | |
Node tortoise, hare; | |
if (start == null) | |
return start; | |
for (tortoiseSpeed = 0; true; tortoiseSpeed = hareSpeed + 1) { | |
if (start.jump(tortoiseSpeed+1) == null) | |
return null; | |
for (hareSpeed = 1; tortoiseSpeed >= 0; hareSpeed++, tortoiseSpeed--) { | |
tortoise = start.jump(tortiseSpeed); | |
hare = tortoise.jump(hareSpeed); | |
if (tortoise == hare) | |
return hare; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment