我們要保證快慢指針相遇時的迭代次數相同,于是快慢指針應該時從相同的位置出發,但是循環跳出的條件時相等,于是將快慢指針都前進一次。本題利用了相遇點總是距離環的起點的位置為L-S這一性質。L是環的長度,S是環的入點距離鏈表起點的位置。
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null) return null;
ListNode fast = head.next.next ;
ListNode slow = head.next ;
while(fast!=slow)
{
if(fast==null||fast.next==null)
return null;
fast=fast.next.next;
slow=slow.next;
}
// now meet
fast=head;
while(slow!=fast)
{
fast=fast.next;
slow=slow.next;
}
return fast;
}
}