您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Linked List Cycle II

Linked List Cycle II

来源:二三娱乐

Description:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

Link:

解题方法:

image.png
用快慢指针可以得知链表是否有环。
如上图所示,假如链表起点为X,环入口为Y,快慢指针第一次在Z点相遇。X->Y = a,Y->Z = b,Z->Y = c。
则有: 2(a + b) = a + n(b + c) + b
即:a = n(b + c) - b
也就是说,如果用两个指针分别从X和Z往下走,一定会在Y点相遇,也就是所求的环的起点。

Time Complexity:

O(N)

完整代码:

class Solution 
{
public:
    ListNode *detectCycle(ListNode *head) 
    {
        ListNode* slow = head;
        ListNode* fast = head;
        do
        {
            if(fast == NULL || fast->next == NULL)
                return NULL;
            slow = slow->next;
            fast = fast->next->next;
        }
        while(fast != slow);
        slow = head;
        while(slow != fast)
        {
            if(slow == NULL || fast == NULL)
                return NULL;
            slow = slow->next;
            fast = fast->next;
        }
        return fast;
    }
};

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务