leetcode 142.
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Solution. First of all, we know that we can use slow / fast pointer to check if it has cycle.
Assume they meet at point Z. We know slow walks distance of a + b, fast walks a + b + c + b. And we know fast walks 2 times as slow. So we have 2 * (a + b) = a + 2b + c. So we conclude a = c.
Since a = c, points from X and Z can meet at Y by walking a(c) distance.
public ListNode detectCycle(ListNode head) { ListNode slow = head, fast = head; while (true) { if (fast == null || fast.next == null) { return null; } slow = slow.next; fast = fast.next.next; if (slow == fast) { break; } } while (head != fast) { head = head.next; fast = fast.next; } return head; }
Check my code on github.