irborrero
9/24/2019 - 1:07 AM

detectCycle

public class Solution {
    public boolean hasCycle(ListNode head) {
        //TODO: error checks
        if(head == null) return false;
        
        ListNode slow = head;
        ListNode fast = head;  
        while(true) {  
            
            slow = slow.next;  
            if(fast.next != null)
                fast = fast.next.next; // 2 hops
            else
                return false;          // next node null => no loop

             if(slow == null || fast == null) // if either hits null..no loop
                return false;

            if(slow == fast) // if the two ever meet...we must have a loop
                return true;
        }
    }
}