I am doing some HankerRank challenges to practice algorithms/data structures, and I am having trouble. The problem is to detect loops in a singly linked list. This is an obvious use of Floyd's cycle finding algorithm, but I can't seem to get it to work. I also checked my answer to others, and it seems to be doing the same thing. If anyone can help me out I would appreciate it.
// Complete the hasCycle function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
static boolean hasCycle(SinglyLinkedListNode head) {
// https://stackoverflow.com/questions/2663115/how-to-detect-a-loop-in-a-linked-list
SinglyLinkedListNode start = head;
//there is no list
if(start == null) {
return false;
}
// have both start at beginning
SinglyLinkedListNode slow = head;
SinglyLinkedListNode fast = head;
while(true) {
slow = slow.next; //hop one ahead
//fast.next may be null, so fast.next.next will cause a null pointer exception
if(fast.next != null) {
fast = fast.next.next; //hop two ahead
} else {
return false;
}
//They are the same node so 'slow' must have caught up
if(slow == fast) {
return true;
}
//We reached the end of the list with no next, so there must not be a loop
if(slow == null || fast == null) {
return false;
}
}
}
Thanks for any advice.
****EDIT**** Sorry for being unclear about what the problem is. When running it on HackerRank, the following input: 1 1 3 1 2 3, fails. My code returns that there is no cycle, when the correct answer is that there is a cycle.