hanCodeHub
3/13/2020 - 7:12 PM

Floyd's Linked List Cycle

Given a linked list, determine if it has a cycle in it.

This is Floyd's Linked List Cycle algorithm, or Tortoise and the Hare algorithm with 1 pointer moving faster than the other until they meet.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        
        ListNode slow = head;  // tortoise pointer
        ListNode fast = head.next;  // hare pointer
        
        // race both pointers until they meet
        while (fast != null && fast.next != null) {
            if (slow.val == fast.val) return true;
            
            slow = slow.next;
            fast = fast.next.next;
        }
        
        // no cycle
        return false;
    }
}