Created
March 13, 2018 18:10
-
-
Save kanikash4/fbf0898aeda86718228f97fe6a3891f4 to your computer and use it in GitHub Desktop.
detect a loop in linked list using slow and fast pointer
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
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