classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: D={} p=head k=0 while p: if p in D: return p else: D[p]=k k+=1 p=p.next returnNone
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: slow=head fast=head while slow and fast: slow=slow.next if fast.nextisNone: fast=None elif fast.nextisnotNone: fast=fast.next.next if slow==fast: break # pattern match exit of loop if fast isNone: returnNone elif fast isnotNone: fast=head while slow!=fast: slow=slow.next fast=fast.next return slow
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: slow=head fast=head while fast and fast.next: slow=slow.next fast=fast.next.next if slow==fast: break # because our while has two exit, so we need to discuss if fast isNoneor fast.nextisNone: returnNone elif fast and fast.next: fast=head while fast!=slow: fast=fast.next slow=slow.next return fast