您的位置:首页 > 其它

(2)寻找链表中环的位置

2015-09-02 14:40 295 查看
算法(1)中,我们已经知道如何判断一个链表中是否有环了,那么怎么找到环的位置呢?

英文命题:

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?

解析:思路非常简单,但我们找到环后,立刻把“快指针”移动到头节点,然后,对“快指针”每次向后移动一步,当这个“快指针”和“慢指针”再次相等时,返回指针就好了。

代码:

ListNode *detectCycle(ListNode *head) 
{
    if(!head) 
    {
        return nullptr;
    }

    ListNode * slow = head;
    ListNode * fast = head;

    while(slow->next && fast->next && fast->next->next)
    {
        slow = slow->next;
        fast = fast->next->next;

        //如果找到了环,将fast指针重新设置为head,并每次移动一步,当它再次和slow相同时就是环的起点
        if(slow == fast)
        {
            fast = head;
            while(slow != fast)
            {
                fast = fast->next;
            }

            return fast;
        }
    }

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