Skip to content

Instantly share code, notes, and snippets.

@francisco-perez-sorrosal
Created January 23, 2012 15:38
Show Gist options
  • Save francisco-perez-sorrosal/1663841 to your computer and use it in GitHub Desktop.
Save francisco-perez-sorrosal/1663841 to your computer and use it in GitHub Desktop.
Code to detect loops in linked lists in O(n)
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