public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head; //fast一次走两步 slow一次走一步
ListNode slow = head; //这样效率最高
if(fast == null) { //若fast为null 则返回null
return null;
}
while(fast != null && fast.next != null) { //还未遍历完,fast slow继续走
fast = fast.next.next;
slow = slow.next;
if(slow == fast) { //slow追上fast 则有环
break;
}
}
if(fast == null || fast.next == null) {
return null;
}
//以上判断链表是否有环
slow = head; //有环的情况下 让slow=this.head
while (fast != slow) { //相遇时既是环的入口点
fast = fast.next;
slow = slow.next;
}
return slow;
}
}