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?
分析:
1、首先判断是否存在循环,见Linked List Cycle
2、若存在循环,则作以下分析
参考:http://blog.csdn.net/sbitswc/article/details/27584037
ListNode *detectCycle(ListNode *head)
{
if(head == NULL)
return NULL;
ListNode* pslow = head;
ListNode* pfast = head;
while(pfast != NULL && pfast->next != NULL)
{
pslow = pslow->next;
pfast = pfast->next->next;
if(pfast == pslow)
break;
}
if(pfast == NULL || pfast->next == NULL)
return NULL;
pslow = head;
while(pslow != pfast)
{
pslow = pslow->next;
pfast = pfast->next;
}
return pslow;
}
已AC 64ms