思路:
![](https://i-blog.csdnimg.cn/blog_migrate/39966aca3fc78e2434b2f0519ac66a88.jpeg)
代码:
/**
* 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 fast=head;
ListNode slow=head;
ListNode index1=head;
ListNode index2=head;
int flag=0;
//判断是否有环
while(fast!=null&&fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
//相遇,终止循环,flag值改变
if(fast==slow)
{
index1=head;
index2=fast;
flag=1;
break;
}
}
//没有环
if(flag==0)
return null;
//有环,找入口点
while(index1!=index2)
{
index1=index1.next;
index2=index2.next;
}
//返回入口点
return index1;
}
}