Linked List Cycle

Linked List Cycle

Coding Solution

·

1 min read

Problem

Given the head of a linked list, determine if the linked list has a cycle in it. This is similar to the Leetcode Problem - Linked List Cycle

Solution

The approach would be simple, take 2 pointers, slow as turtle and fast as hare. When the turtle is equal to the hare, cycle is found.

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode hare = head;
        ListNode turtle = head;
        while(hare!=null && hare.next !=null) {
        turtle = turtle.next ;
        hare = hare.next.next;
            if(hare == turtle)
                return true;
        }
        return false;    
    }
}

Do have a look at the discuss section for more optimized solutions if available - LeetCode Discuss