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 nullDo 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

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break