[LeetCode] 142. Linked List Cycle II

来源:互联网 发布:计数排序算法 编辑:程序博客网 时间:2024/06/05 19:42

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?

/*该题在第一题的基础之上,要求检测出循环的入口处。检测循环的算法,同第一题,核心思想就是一个跑的快的人,一个跑的慢的人,结局无非是跑的快的人先到达终点(无循环存在),或是跑的快的人追上了跑的慢的人(循环存在)。令L1表示从出发点到循环入口处的距离令L2表示从循环入口处到快慢二人碰面处的距离令C表示循环的长度令n1, n2分别表示二人在循环内所绕的圈数则慢的人跑的距离为 L1 + L2 + n1 * C快的人跑的距离为 L1 + L2 + n2 * C同时,由于快的人的速度是慢的人的两倍,可得下式2(L1 + L2 + n1 * C) = L1 + L2 + n2 * C即L1 = (n2 - n1 - 1) * C + (C - L2)也就是说,从出发处到循环入口处的距离和从碰面处到循环入口处的距离(当然这中间可能绕了好多犬)是相等的。简单来说,一个人从出发处出发,一个人从循环碰面处出发,以同样的速度前进,那么最终二者必将会在循环入口处相遇。*/class Solution {public:    ListNode *detectCycle(ListNode *head) {        if (head == nullptr || head->next == nullptr)            return nullptr;        ListNode *slow = head, *fast = head;        while (fast->next && fast->next->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) {                ListNode *entry = head;                while (slow != entry) {                    slow = slow->next;                    entry = entry->next;                }                return entry;            }        }        return nullptr;    }};

这里写图片描述
这里写图片描述

原创粉丝点击