142. Linked List Cycle II
Given the head
of a linked list, return the node where the cycle begins. If there is no cycle, return null
. Do not modify the linked list.
def detectCycle(self, head: Optional[ListNode]):
if head is None:
return None
fast, slow = head, head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast is None or fast.next is None:
return None
intersect = fast
first = intersect, second = head
while first != second:
first = first.next, second = second.next
return first
Comments
Post a Comment