

java
/**
* 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) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
//快指针走两步慢指针一步
slow = slow.next;
fast = fast.next.next;
//快慢指针相遇
if(slow == fast){
ListNode index1 = slow;
ListNode index2 = head;
//两指针一步一步走
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
假设a表示从起点到环入口的距离;b表示从环入口到相遇点的距离;c表示从相遇点继续往前走到环入口的距离。
慢节点走过的距离:a+b
快节点走过的距离:a+b+n(b+c),表示快节点在圈中多转了n圈
快节点是慢节点的两倍,所以2(a+b)=a+b+n(b+c)
a+b=n(b+c)
a=n(b+c)-b
a=(n-1)(b+c)+c
a的长度等于快节点在环里面转(n-1)圈后再走c的长度
所以将慢节点放到head,快节点放到相遇位置,然后以相同速度前移,最终会得到相遇的位置