142. Linked List Cycle II
Approach
Problem Analysis
This type of linked list problem is generally solved using the two-pointer technique — for example, finding the node at distance K from the tail, finding the cycle entrance, or finding the intersection node.
Algorithm
-
First meeting of two pointers: Set two pointers
fastandslowboth pointing tohead.fastmoves 2 steps per round,slowmoves 1 step per round.a. Case 1: If
fastreaches the end of the list, the list has no cycle — returnnull.Tip: If there is a cycle, the two pointers will definitely meet. Each round, the gap between
fastandslowdecreases by 1, sofastwill eventually catchslow.b. Case 2: When
fast == slow, the two pointers meet for the first time inside the cycle. Let's analyze the steps taken:Suppose the list has
a + bnodes in total, withanodes from the head to the cycle entrance (not counting the entrance node), andbnodes in the cycle. Letfandsbe the steps taken by each pointer:fasttravels twice the steps ofslow:f = 2sfasttravelsnextra cycles compared toslow:f = s + nb- From the above:
f = 2nb,s = nb— both pointers have walked an integer multiple of the cycle length.
-
Current situation analysis:
If a pointer walks
ksteps fromhead, it reaches the cycle entrance whenk = a + nb(afterasteps it reaches the entrance; each additional cycle ofbsteps brings it back to the entrance).Currently,
slowhas walkednbsteps. So we just needslowto walkamore steps to reach the cycle entrance.But we don't know
a. We use a second pointer starting fromhead. When this pointer andslowboth walkasteps together, they meet exactly at the cycle entrance. -
Second meeting of two pointers: Keep
slowin place, resetfasttohead. Both move forward 1 step per round.When
fasthas walkedasteps:slowhas walkeda + nbsteps. The two pointers meet and both point to the cycle entrance. -
Return the node pointed to by
slow.
Complexity Analysis
Time complexity O(N): In the second encounter, the slow pointer walks a < a + b steps. In the first encounter, the slow pointer walks a + b − x < a + b steps (where x is the distance from the meeting point to the entrance). The overall complexity is linear.
Space complexity O(1): The two pointers use constant extra space.
Code
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
a = head
b = head
while True:
if not b or not b.next:
return None
a = a.next
b = b.next.next
if b == a:
break
b = head
while a != b:
a, b = a.next, b.next
return bclass Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *a = head;
ListNode *b = head;
while (true) {
if (!b or !b->next) {
return nullptr;
}
a = a->next;
b = b->next->next;
// because b moves two steps each time, a and b must meet
if (a == b) {
break;
}
}
// After meeting, keep a in place, reset b to head
b = head;
while(a!=b){
a = a->next;
b = b->next;
}
return a;
}
};贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0