- 环形链的入口
慢指针:a+b
快指针:a+b+c+b
快指针的速度是慢指针的两倍,则 a+b+c+b = 2*(a+b),化简得a=c,则可以将两指针分别放在起始位置和相遇位置,并以相同速度前进,当一个指针走完距离a时,另一个指针恰好走完c,此时两个指针所在的位置就是环的入口处。
import java.util.*;
/**
* 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 fastNode = head;
ListNode slowNode = head;
if(head == null) {
return null;
}
//先判断是否有环
while(fastNode != null && fastNode.next != null && fastNode.next.next != null) {
fastNode = fastNode.next.next;
slowNode = slowNode.next;
if(fastNode == slowNode) {
fastNode = head;
while(fastNode != slowNode) {
fastNode = fastNode.next;
slowNode = slowNode.next;
}
return slowNode;
}
}
return null;
}
}