You are given the head of a linked list. Determine if the linked list has a cycle. If a cycle is present, find the length of the cycle. If no cycle is present, return 0.
We have already discussed the detection of linked list - here.
classSolution:
defgetCycleLength(self, head: ListNode) -> int:
slow, fast = head, head
# Step 1: Detect cycle using Floyd’s Tortoise and Hare Algorithmwhile fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast: # Cycle detectedreturn self.findCycleLength(slow)
# No cyclereturn0deffindCycleLength(self, nodeInCycle: ListNode) -> int:
current = nodeInCycle
length =0whileTrue:
current = current.next
length +=1if current == nodeInCycle:
breakreturn length