原题链接https://leetcode.cn/problems/linked-list-cycle-ii/
快慢指针法
判断是否有环:定义两个快慢指针fast,low,分别指向head节点,fast每次移动两个节点,low每次移动一个节点。r如果存在环,fast一定会追到low。
找出环的入口:
设head到入口节点的节点数为x,入口到相遇节点的个数为y,相遇节点到入口节点的节点数为z。
相遇时low走过的节点数为x+y,fast走过的节点为x+y+n(y+z),n代表圈数。
因为fast一次走两个节点,所以相遇时满足,,因为要求x,最后化简
,这就意味着从head到入口节点的个数等于从相遇节点走n-圈到再到入口节点的个数。
最后附上代码
public ListNode detectCycle(ListNode head) {
if (head==null){
return null;
}
ListNode fast=head;
ListNode low=head;
while (fast!=null && fast.next!=null){
fast=fast.next.next;
low=low.next;
if (fast==low){
ListNode temp=head;
while (temp!=low){
temp=temp.next;
low=low.next;
}
return temp;
}
}
return null;
}