Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
判断有没有环,如果没有环,返回null
如果发现快慢指针相等了,则说明有环,然后将快指针放到head,慢指针从相遇处,各自一步一步走,再次相遇就是环的入口。
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c。
精确分析:
第一个慢指针走过的路程长度是x1 + x2 + k1 * (x2 + x3)。
第二个快指针走过的路程长度是x1 + x2 + k2 * (x2 + x3)。
由快慢指针的速度关系得:(x1 + x2) * 2 + 2 * k1 * (x2 + x3) = x1 + x2 + k2 * (x2 + x3),因此x1 + x2 = (k2 - 2 * k1) * (x2 + x3),进而有x1 - x3 = (k2 - 2 * k1 - 1) * (x2 + x3)。
这说明x1和x3的距离差值刚好是环长(x2 + x3)的整数倍。 因此,我们只需令其中一个指针指向虚拟头节点,而另一个指针则仍然在相遇的那个节点,一起移动这两个指针,直到这两个指针相遇,这个新的相遇点就是链表开始入环的第一个节点。
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
// 找到环以后,fast放到head,然后再走,再相遇,相遇的节点就是入口
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}