python leetcode 142. Linked List Cycle II

先判断是否是环。假设环长为L,不是环的长度为M,在环中的N处相遇。那么fast走了M+K1L+N,slow走了M+K2L+N。fast=2slow,M+K1L+N=2*(M+K2*L+N),N=(K1-K2)*L-M。可以看到从N出发再走M就到了环的起始点。

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next ==None:
            return None 
        fast = head 
        slow = head 
        while fast and fast.next:
            
            fast = fast.next.next 
            slow = slow.next 
            if fast == slow:
                break 
        if fast == slow:
            slow = head 
            while slow != fast:
                slow = slow.next 
                fast = fast.next 
            return slow 
        return None

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84997730
今日推荐