套路:
快慢指针,当两指针相遇时,快指针回到头结点,两个指针继续同步移动一步,直到第二次相遇即为所求。
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return slow
return