# Leetcode 142. Linked List Cycle II

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.

Can you solve it without using extra space?

# 分析

``````/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *array;
int num=0;
while(p!=NULL)
{
for(int i=0;i<num;i++)
{
if(p==array[i])
return array[i];
}
array[num]=p;
num++;
p=p->next;
}
return NULL;
}
``````

using two pointers, one of them one step at a time. another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so…2k-k=nr,k=nr
Now, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node is m, so…s=k-m,
s=nr-m=(n-1)r+(r-m),here we takes n = 1…so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.

``````ListNode *detectCycle(ListNode *head) {

bool isCycle = false;

while(firstp != NULL && secondp != NULL) {
firstp = firstp->next;
if (secondp->next == NULL) return NULL;
secondp = secondp->next->next;
if (firstp == secondp) { isCycle = true; break; }
}

if(!isCycle) return NULL;