您的位置:首页 > 其它

LeetCode Linked List Cycle II(找到带环单向链表的环起始位置)

2014-04-06 11:52 676 查看
题目要求:

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?

如果链表存在环,要求找到环的首节点, 如果不存在返回null.

解析:

先看这个图,



设A到D得距离为k, 当slow指针走了k步, fast指针则走了2k步。 设环的长度为N. 当slow指针到达D时, fast走了2k步, 在环外走了k,在环内走了k步,因为k可能大于N,我们让 k = k%N; 所以slow比fast慢了k步, fast需要追赶N-K 步,因为每一次移动fast比slow快1步,所以需要N-K次移动,
相当于slow在环里走了N-K步后在I点相遇。此时很容易得到I到D得距离应该是K. 所以此时将slow移到head处, 然后fast与slow以相同的速度移动,相遇处就是换的开始节点D。

代码:

class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
if (head ==NULL) {
return NULL;
}
ListNode* slow_ptr = head, *fast_ptr = head;
while(fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
if(fast_ptr == NULL)
return NULL;
slow_ptr = slow_ptr->next;
if(fast_ptr == slow_ptr)//第一次相遇
{
slow_ptr = head;
while(fast_ptr != slow_ptr)//找第二次相遇
{
slow_ptr = slow_ptr->next;
fast_ptr = fast_ptr->next;
}
return fast_ptr;
}
}
return NULL;

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