The description of the problem
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return nulll.
There is a cycle in a linked list if there is some nodes in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list.
The codes in C++
/**
* 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) {
ListNode* fastNode = head;
ListNode* slowNode = head;
while (fastNode && fastNode->next) {
fastNode = fastNode->next->next;
slowNode = slowNode->next;
if (fastNode == slowNode) {
ListNode* indexNode_1 = head;
ListNode* indexNode_2 = fastNode;
while (indexNode_1 != indexNode_2) {
indexNode_1 = indexNode_1->next;
indexNode_2 = indexNode_2->next;
}
return indexNode_1;
}
}
return NULL;
}
};
The codes in python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
else:
return None
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return fast