1classSolution:2defoverlappingListsCycles(self, headA, headB):3 cycleA, cycleB = self.startOfCycle(headA), self.startOfCycle(headB)45ifnot cycleA andnot cycleB:return self.overlappingLists(headA, headB)6elif(not cycleA and cycleB)or(not cycleB and cycleA):returnNone78 tmp = cycleA.next9while tmp and tmp != cycleB: tmp = tmp.next1011return tmp if tmp == cycleB elseNone1213defoverlappingLists(self, headA, headB):14 first, second = headA, headB
1516while first and second and first != second:17 first = headB ifnot first else first.next18 second = headA ifnot second else second.next1920return first
2122defstartOfCycle(self, node):23 fast, slow = node, node
24while fast and fast.next:25 slow = slow.next26 fast = fast.next.next27if slow == fast:break2829if slow: length = self.cycleLength(slow)30else:returnNone3132 first, second = slow, node
33for _ inrange(length):34 first = first.next35 second = second.next3637return first
3839defcycleLength(self, node):40 res, n =1, node.next41while n != node:42 res +=143 n = n.next4445return res