题目
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解法:
题目的意思就是判断链表中是否有环,并找出环的起始位置
o(n)的解法就是设置两个指针fast和slow,fast每次往前走两步,slow走一步,如果链表中有环,那么fast和slow迟早会相遇。
则相遇时,slow走过的位置为a+b,fast走过的位置为a+b+c+b,因为fast走过的距离是slow的二倍,所以a+b+c+b=2(a+b),则c=a。
我们首先可以求出fast和slow的相遇位置,然后将一个移到相遇位置,一个移到链表的最开始,以相同速度前进,相遇位置则为其实点
代码
/**
* 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;
if(head->next == NULL)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
ListNode *meetnode;
while(1)
{
fast = fast->next;
if(fast == NULL)
return NULL;
fast = fast->next;
if(fast == NULL)
return NULL;
slow = slow->next;
if(fast == slow)
{
meetnode = fast;
break;
}
}
fast = head;
slow = meetnode;
// ListNode *ans;
while(1)
{
if(fast == slow)
break;
fast = fast->next;
slow = slow->next;
}
return fast;
}
};