Floyd's Cycle Detection Algorithm


  • 0
    M
    public boolean hasCycle(ListNode head) {
            
            /**
             * The below algorithm is an example of Floyd's cycle detection algorithm
             * which uses 2-pointers approach
             **/
            
            ListNode slow = head;
            ListNode fast = head;
            
            while (slow != null && fast!= null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                
                if (slow == fast) {
                    return true;
                }
            }
            return false;
        }
    

Log in to reply
 

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