您的位置:首页 > 其它

Linked List Cycle II

2014-04-18 21:51 344 查看
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?

快慢指针,只要S和F相遇了,我们拿一个从头开始走,一个从相遇的地方开始走

两个都走一步,那么再次相遇必定是环的开始节点!

参考http://www.cnblogs.com/x1957/p/3406448.html
ListNode *detectCycle(ListNode *head)
{
if(head==NULL)
return NULL;

ListNode *slow = head, *fast = head;

while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)// first meet
{
slow=head;
while(slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;// second meet
}
}

return NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: