判断链表是否有环,若有,返回环的起始节点。
思路:快慢指针。若有环,则快慢指针必定相遇。
public ListNode detectCycle(ListNode head) {
if(head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){ //说明有环,此时的fast和slow相遇点不一定是环的入口点
slow = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}