定义快慢指针fast,slow,fast一次走两步,slow一次走一步,双指针在环中必定相遇
快慢指针环中必定相遇
当slow第一次进环,fast已经走了一段,记slow和fast距离为N,fast开始追slow
slow每走1步,fast走2步
每追1次,fast和slow的距离-1
N-1-1-1-1-1...=0
当N=0时,fast和slow 相遇
回环链表检测入环点
假设
链表头(head)到入环点(in)的距离为:L
入环点(in)到相遇点(meet)的距离为:X
环长度为:C
fast前进的距离始终为slow的2倍,当fast和slow相遇时,fast最少绕环一圈(路短环大则一圈,路长环小则多圈),推出
2(L+X)[slow前进的距离*2] = L+N*C+X[fast前进的距离]
分解式子
2L+2X = L+X+N*C
L=N*C一X
L=(N一1)C+C一X
当N为最小值1时,L=C一X
得出,当双指针在相遇点(meet)相遇时,slow指针和head指针开始同时前进,L距离后,head和slow相遇,相遇点即为入环点(in)
代码实现如下:
struct ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
struct ListNode* meet = slow;
while (meet != head) {
meet = meet->next;
head = head->next;
}
return meet;
}
}
return NULL;