Linked Lists: Detect a Cycle

  • + 29 comments

    Java solution using fast and slow pointers, no need for a HashSet.

    boolean hasCycle(Node head) {
        if (head == null) return false;
        
        Node slow = head;
        Node fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) return false;
            
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return true;
    }