# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defdetectCycle(self, head):"""
:type head: ListNode
:rtype: ListNode
"""if head isNoneor head.nextisNone:returnNone
slow = head
fast = head.next# 找环 只有fast与slow相遇才会有环while fast and fast.nextand fast != slow:
slow = slow.next
fast = fast.next.next# 无环 返回Noneif fast isNoneor fast.nextisNone:returnNone# 计算环的大小
cnt =1
node = fast.nextwhile node != slow:
node = node.next
cnt +=1# 让fast提前走一个环的长度
fast = head
for _ inrange(cnt):
fast = fast.next# 因为fast比slow提前走了一个环,所以fast与slow相遇的位置就是入口
slow = head
while fast != slow:
fast = fast.next
slow = slow.nextreturn fast