第一百四十二题:网上借鉴
1.边界情况:
根结点为空。
2.思路:
首先要判断是否有环,利用141题中的方法,接着假设链表起点为A,环的起点为B,两指针在D点相遇,AB长为a,环长r,BD长为b,DB长为d,如图;
设快指针速度为v1,慢指针速度为v2,相遇时间为t,v1所走完整圈数为n
v1t = a + b + nr
v2t = a + b
2a + 2b = a + b + nr
a + b = nr
a + b = (n-1)r + r
a + b = (n-1)r + b + d
a = (n-1)r + d
即a = d
所以在相遇处设一指针a和指针b在链表头处,两个指针同时以1步/次的速度前进,最后会在环的开始处相遇,问题得解。
ListNode *detectCycle(ListNode *head) {
ListNode* first = head;
ListNode* second = head;
while (first != NULL&&second != NULL&&second->next != NULL){
first = first->next;
second = second->next->next;
if (first == second){
first = head;
while (first != second){
first = first->next;
second = second->next;
}
return first;
}
}
return NULL;
}