142.Linked List Cycle II

```

/**
 * 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 || head.next == null){
            return null;
        }
        else{
            ListNode slow = head;
            ListNode fast = head;
            boolean isCycle = false;
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
                //Find Cycle
                if(slow == fast){
                    isCycle = true;
                    break;
                }

            }
            if(!isCycle)
                return null;
            else{
                slow = head;
                while(slow != fast){
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
            }
        }
    }
}

results matching ""

    No results matching ""