Posted by chunyang on April 27, 2019

### 题目

#### 题目一

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

#### 题目二

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

### 解法

#### 思路

• 慢指针每次移动一步
• 快指针每次移动两步

• collision point 往前走一步，得到 p
• head 和 p 一直往前走，二者相遇的点即为 connection point

• 慢指针移动：n = h + d
• 快指针移动：2n + 1 = h + d + m * c

h = qc + r, 可以得到 d = c - r -1

h+d = h + c - r -1 = qc + r + c - r -1 = (q+1) * c - 1，从这点再移动 h+1 步得到

(q+1) * c + h，这个和头结点到 connection point 是一样的。

#### 代码

class Solution {
public:
while (slow != fast) {
slow = slow->next;
if (!fast) return fast;
fast = fast->next;
if (!fast) return fast;
fast = fast->next;
}

// return fast; // we get collision point

// fast is collision point

fast = fast->next;