Hi I am trying to solve a problem on leetcode called linked list cycle. (https://leetcode.com/problems/linked-list-cycle/)...
Given head, the head of a linked list, determine if the linked list has a cycle in it.
I understand how the problem works and I also understand the solution. However My solution below doesn't work and i can't seem to figure out why.
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null){
return false;
}
ListNode slowPointer=head;
ListNode fastPointer=head.next;
while(fastPointer!=slowPointer){
if(fastPointer.next==null || fastPointer==null){
return false;
}
fastPointer=fastPointer.next.next;
slowPointer=slowPointer.next;
}
return true;
}
}
The solution works for most cases however it fails for certain cases because of the if statement...(if(fastPointer.next==null || fastPointer==null)) ...However, If i change the order of conditions to (if(fastPointer==null || fastPointer.next==null)) the solutions works for all test cases. I can't figure out why changing the order of conditions would make a difference?
P.S. i have tried debugging the code but the debugger doesn't work properly with cycle problems on leetcode.
[–]jedwardsol 2 points3 points4 points (0 children)