Skip to content

Instantly share code, notes, and snippets.

@kanikash4
Created March 13, 2018 18:10
Show Gist options
  • Save kanikash4/fbf0898aeda86718228f97fe6a3891f4 to your computer and use it in GitHub Desktop.
Save kanikash4/fbf0898aeda86718228f97fe6a3891f4 to your computer and use it in GitHub Desktop.
detect a loop in linked list using slow and fast pointer
boolean hasCycle(Node head) {
boolean result = false;
if (head == null) {
result = false;
}
else {
Node slowp = head;
Node fastp = head;
while (fastp != null && fastp.next != null && slowp != null) {
slowp = slowp.next; //increment by 1
fastp = fastp.next.next; //increment by 2
if (slowp == fastp) {
//cycle detected
result = true;
break;
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment