Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
Analysis:
分析:以上图为例,假设从开始点1到cycle开始点4的距离为h,假设fast和slow在点7碰到而且从4到7的距离为a,整个cycle的长度为c;假设fast走了n圈,slow走了m圈,fast走的是slow的两倍那么我们就有
H + n*c + a = 2 ( h
+ m*c + a)
==>
(n-m)c = h + a
也就是说,如果两个指针slow从7开始走,p从head开始走,那么最终他们还是会碰到7这点。因为slow和p的速度是一样的,所以,他们的4,5,6这几点肯定是重合的,那么第一个重合的点就是cycle开始的点。
/**
* 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) {
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(fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}
};
No comments:
Post a Comment