Linked List Cycle II
2015-04-07 15:59 笨笨的老兔子 阅读(151) 评论(0) 编辑 收藏 举报给定一个链表,如果该链表有环,请返回环的起点,否则返回NULL
思路:一个FAST每次前进两步和一个SLOW每次前进一步,当两个指针相等的时候,其中一个回到head,然后两个同时往前走,再次相遇时的位置就是环的起点
证明:
假设第一次相遇时,SLOW走了M步,FAST走了2M步,环的长度是L,相遇点距离环的起点为K,则此时FAST回到起点,距离环的起点为M-K,SLOW距离环的起点为L-K,当FAST走完M-K到达环的起点时,SLOW走了
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head)
{
ListNode* fast = head;
ListNode* slow = head;
while (fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (fast == NULL )
{
return NULL;
}
if (fast == slow)
{
fast = head;
while (fast != slow)
{
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
}
return NULL;
}
};