1. 程式人生 > >python leetcode 142. Linked List Cycle II

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