Leetcode 142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return nullptr
.
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 the tail connects to form a cycle. If pos is -1, then there is no cycle.
Example:
nullptr
if there’s no cycle.To detect the cycle and find the starting node of the cycle, we’ll use Floyd’s Tortoise and Hare algorithm:
Here’s the step-by-step code implementation:
/**
* 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) return nullptr;
ListNode *slow = head;
ListNode *fast = head;
// Detect if there is a cycle
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
// Cycle detected, find the entry point of the cycle
ListNode *entry = head;
while (entry != slow) {
entry = entry->next;
slow = slow->next;
}
return entry; // The start of the cycle
}
}
return nullptr; // No cycle
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?