public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null) return null;
ListNode slow=head,fast=head;//快慢指针
boolean loop=false;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(fast==slow) {
loop=true;break;//快慢指针相遇,环存在
}
}
if(loop){
slow=head;
while(slow!=fast){
fast=fast.next;//快慢指针同时移动,相遇处为环开始处
slow=slow.next;
}
return slow;//返回索引
}
return null;
}
}