判断链表中是否有环的算法就是利用快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null)return false;
ListNode slow=head;
ListNode fast=head.next;
while(fast.next!=null&&fast.next.next!=null){
if(slow==fast)return true;
fast=fast.next.next;
slow=slow.next;
}
return false;
}
}
但是判断环的入口就有点麻烦了:
a:出发
b:入口点
c:快慢指针相遇点
只要知道ab需要走多少步,就确定了入口。
相遇的时候,慢指针从a走到了c,快指针从a出发,在环里面绕了n(n>1)圈到c相遇, 快-慢=n圈
快=2慢,2ac-ac=ac=ab+bc=n圈,那么ab=n圈-bc=(n-1)圈+(1圈-bc);所以从等式可以看出,从a出发到b相当于从c出发走(n-1)圈再走cb段:
import java.util.*;
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null)return null;
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
ListNode fast1=head;
while(fast1!=slow){
fast1=fast1.next;
slow=slow.next;
}
return slow;
}
}
return null;
}
}