Floyd's cycle finding in Java, 1 ms


  • 0
    R
     // Floyd’s cycle finding algorithm, also called the Tortoise and hare algorithm.
      //use two pointers, one moving twice as fast
    public boolean hasCycle(ListNode head) {
        if(head==null) return false;
        ListNode slow=head;
        ListNode fast=head;
        do{
            if(fast.next==null||fast.next.next==null)
                return false;
            fast=fast.next.next;
            
            slow=slow.next;
        }
        while(fast!=slow);
        
        return true;  //if the loop exists, found meeting point
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.