/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ publicclassSolution{ public ListNode detectCycle(ListNode head){ ListNode fast = head, slow = head; boolean isCycle = false; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) { isCycle = true; break; } } // # of fast = 2 * # of slow = # of meeting node + circle = # of slow + circle // => # of slow = circle // distance from head to the circle entry = distance from meeting node to circle entry if (!isCycle) returnnull; while (head != slow) { head = head.next; slow = slow.next; } return head; } }