LC 0142 [M] Linked List Cycle II - ALawliet/algorithms GitHub Wiki

# 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]:
        fast = slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                break # there must be a cycle and slow and fast are on the cycle
        else: # got to the end without breaking
            return None  # if not (fast and fast.next): return None
        
        while head != fast:
            head = head.next
            fast = fast.next
        return head