[Leetcode] 142. Linked List Cycle II 解题报告

来源:互联网 发布:matlab算法工具箱 编辑:程序博客网 时间:2024/04/29 17:53

题目

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?

思路

在Leetcode 141的基础上,我们来推导一下怎么确定环的入口。假设有环,那么慢指针最多走n步(即回到头部)就会和快指针相遇。以盗的图为例,假如从链表头部到环入口的长度为k(即D的位置),快慢指针相遇在E,从相遇的节点到环入口的长度为y。在相遇的时候快指针多走了一圈环行,那么快慢指针到相遇的时候各走的步数是:

slow = k + x;

fast = k + x + y + x.

因为快指针速度比慢指针快一倍,因此会有如下关系:fast = 2 * slow,即:(k + x + y + x) = 2 * (k + x),可以得出k = y。因此现在从快慢指针相遇的地方到环入口和从链表头部到环入口的距离相等。所以让快慢指针以相同的速度从这两个地方再开始走,到相遇的地方就是即为环的入口(本题的分析部分参考了小榕流光的博客:http://blog.csdn.net/qq508618087/article/details/50473996)。算法的时间复杂度仍然是O(n),空间复杂度O(1)。


代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head) {        if (head == NULL) {            return NULL;        }        ListNode *slow = head, *fast = head;        while (fast->next && fast->next->next) {            slow = slow->next;            fast = fast->next->next;            if (slow == fast) {                fast = head;                while (fast != slow) {                    fast = fast->next;                    slow = slow->next;                }                return slow;            }        }        return NULL;    }};

0 0