Created
January 23, 2012 15:38
-
-
Save francisco-perez-sorrosal/1663841 to your computer and use it in GitHub Desktop.
Code to detect loops in linked lists in O(n)
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
public static boolean containsLoop(LinkedListNode list) { | |
LinkedListNode slowIterator = list, fastIterator = list; | |
// If a loop exists in the list, both iterators will be going round | |
// and round in the loop, and at some point, they will be equal | |
while (slowIterator != null && fastIterator != null) { | |
slowIterator = slowIterator.getNext(); | |
try { | |
fastIterator = fastIterator.getNext().getNext(); | |
} catch (NullPointerException npe) { | |
fastIterator = null; | |
} | |
if (slowIterator == fastIterator) | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment