Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
是一个快慢指针的问题。
在环中相遇,就好比让甲的速度是乙的2倍,在操场上跑步,那甲在第2圈一定能和乙相遇。
所以设一个快指针,一个慢指针,快指针每次走2步,慢指针每次走一步。如果有环,它们就会相遇。
相遇时,快指针和慢指针指向的是同一个节点。
这时让慢指针回到head,慢指针和快指针都每次走一步,等它们再次相遇的时候,就是环的起点。
至于为什么快指针要是慢指针速度的2倍,为什么相遇后每次走一步再次相遇时就是环的起点,如何证明,
参考此文,讲的还是比较清楚的。
public ListNode detectCycle(ListNode head) {
if(head == null) return null;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}