![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/be8f0cbbc025986baf70edf5cbd9853a.jpeg)
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null||head.next.next==null)
return null;
ListNode slow=head.next;
ListNode fast=head.next.next;
while (fast!=slow&&fast!=null&&fast.next!=null) {
fast=fast.next.next;
slow=slow.next;
}
if(fast==null||fast.next==null)
{
return null;
}else{
fast=head;
while(fast!=slow)
{
fast=fast.next;
slow=slow.next;
}
}
return slow;
}
public static void main(String[]args){
ListNode head=new ListNode(1);
head.next=new ListNode(2);
head.next.next=new ListNode(3);
ListNode tmp=new ListNode(4);
head.next.next.next=tmp;
tmp.next=head.next;
Solution s=new Solution();
System.out.println(s.detectCycle(head).val);
}
}