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?
思路:双指针判断是否有环,然后计算环的结点个数,再找出倒数第n个结点即环的入口结点。
代码:
ListNode *detectCycle(ListNode *head) {
ListNode *p=head;
ListNode *q=head;
while(q!=NULL && q->next!=NULL)
{
p=p->next;
q=q->next->next;
if(p == q)
{
break;
}
}
if(p==q && p!=NULL && p->next!=NULL)
{
int count=1;
p=p->next;
while(p!=q)
{
p=p->next;
count++;
}
p=head;
q=head;
while(count>0)
{
q=q->next;
count--;
}
while(p!=q)
{
p=p->next;
q=q->next;
}
return p;
}
else
return NULL;
}