Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Try solving it using constant additional space.

Example :

Input : 

                  ______
                 |     |
                 \/    |
        1 -> 2 -> 3 -> 4

Return the node corresponding to node 3. 

 


/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution 
{
    public ListNode detectCycle(ListNode head) {
        
        if(head==null) return null;
        
        ListNode slow = head, fast = head;
        
        try {
            do {
                fast = fast.next;
                fast = fast.next;
                slow = slow.next;
            } while(fast!=null && fast!=slow);
            
        } catch(Exception e){}
        
        if(slow==null || fast==null || slow!=fast)
            return null;
            
        slow = head;
        
        while(slow!=fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *