classSolution:defdetectCycle(self, head: Optional[ListNode])-> Optional[ListNode]:
node_set =set()
current = head
while current:if current in node_set:return current
else:
node_set.add(current)
current = current.nextreturnNone
快慢指针法
classSolution:defdetectCycle(self, head: ListNode)-> ListNode:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next# If there is a cycle, the slow and fast pointers will eventually meetif slow == fast:# Move one of the pointers back to the start of the list
slow = head
while slow != fast:
slow = slow.next
fast = fast.nextreturn slow
# If there is no cycle, return NonereturnNone