LeetCode --- Linked List Cycle II

题目链接

题意: 给出单链表,判断是否存在环,如果存在要求输出环开始的结点.

思路及证明:

It is a famous known problem Hare and Tortoise.

Length of head to cycle started node: x

Length of the cycle: y

Let hare run two steps while tortoise runs one step

while both of them entered the cycle, the hare is definetly to overlap the tortoise at some node, we define it as m:

The hare totally runs: x + ky + m The tortoise totally runs: x + ty + m Thus, ky = 2ty + x + m we have (x + m) mod y = 0 We can conclude that if the hare run more x steps, it will reach the cycle's starting node.

附上代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if (head == NULL || head->next == NULL) {
13             return NULL;
14         }
15         ListNode *fast = head, *slow = head;
16         bool flag = false;
17         while (fast != NULL && fast->next != NULL) {
18             slow = slow->next;
19             fast = fast->next->next;
20             if (slow == fast) {
21                 flag = true;
22                 break;
23             }
24         }
25         if (!flag) {
26             return NULL;
27         } else {
28             slow = head;
29             while (slow != fast) {
30                 slow = slow->next;
31                 fast = fast->next;
32             }
33             return slow;
34         }
35     }
36 };
原文地址:https://www.cnblogs.com/Stomach-ache/p/3735017.html