Cover image for LeetCode Hot 100 P142 Linked List Cycle II

LeetCode Hot 100 P142 Linked List Cycle II


Timeline

timeline

2026-03-13

init

linked list, two pointers

Problem:

First meeting, fast pointer has moved2 * ksteps, slow pointer has moved k steps, let length outside cycle be m, cycle length L

Fast pointer has gone n more laps(nL) i.e.k = nL, i.e. slow pointer has movednLsteps

Slow pointer then moves m more steps, totalm+nLsteps to reachm+nL= cycle entrance

Note that the following loop should not use do while, because a linked list may be a circular linked list, and the length outside the cycle is 0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

struct ListNode {
int val;
ListNode *next;
ListNode(int x)
: val(x)
, next(nullptr)
{
}
};

class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
if (head == nullptr)
return nullptr;
ListNode *low = head, *fast = head;

do {
if (fast->next == nullptr || fast->next->next == nullptr)
return nullptr;

fast = fast->next->next;
low = low->next;

} while (low != fast);

// low == fast

low = head;
while (low != fast) {
fast = fast->next;
low = low->next;
}

return low;
}
};