LeetCode |142. 环形链表 II

LeetCode |142. 环形链表 II

OJ链接
LeetCode |142. 环形链表 II_第1张图片

  • 一个指针从相遇点开始走,一个指针从头开始走,它们会在入口点相遇~~
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode* slow,*fast;
    slow = fast = head;
    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast)
        {
            struct ListNode *meet = slow;
            while(head != meet)
            {
                head = head->next;
                meet = meet->next;
            }
            return meet;
        }
    }
    return NULL;
}

你可能感兴趣的:(LeetCode,leetcode,链表)