问题描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up: Can you solve it without using extra space?
解题思路
首先,需要判断链表中有无环,借助快慢指针去寻找,fast每次走两步,slow每次走一步,如果有环两者一定会相遇。
然后,如果有环存在需要返回环的起点,这时把快慢指针中的一个指向head,另一个还在之前相遇的位置,然后两指针以相同速度前进,下一次相遇的位置就是环的起点。
证明如下:
(链接:https://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad
来源:牛客网)
如下图所示,X,Y,Z分别为链表起始位置,环开始位置和两指针相遇位置,则根据快指针速度为慢指针速度的两倍,可以得出:
2*(a + b) = a + b + n * (b + c);即
a=(n - 1) * b + n * c = (n - 1)(b + c) +c;
注意到b+c恰好为环的长度,故可以推出,如将此时两指针分别放在起始位置和相遇位置,并以相同速度前进,当一个指针走完距离a时,另一个指针恰好走出 绕环n-1圈加上c的距离。
故两指针会在环开始位置相遇。
实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
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){//有环
break;
}
}
if(fast == NULL || fast->next == NULL){
return NULL;
}
slow = head;
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
继续学习链表~要多练多练呀