LeetCode 142. Linked List Cycle II

LeetCode 142

这个问题的算法和这个一样 ( Floyd’s Tortoise and Hare 算法)
https://blog.csdn.net/frankguodongchen/article/details/107479459

    def detectCycle(self, head: ListNode) -> ListNode:
        if head == None: return None

        slow = head.next
        fast = slow.next if slow != None else None

        while slow != fast and fast != None:
            slow = slow.next
            fast = fast.next
            if fast != None:
                fast = fast.next

        #no cycle
        if fast == None:
            return None

        slow = head
        while slow != fast:
            slow = slow.next
            fast = fast.next

        return fast

你可能感兴趣的:(Python学习,算法,leetcode)