Skip to content

Commit d7d14fc

Browse files
committed
feat(data-structures, linked-lists): cycle length
1 parent 0b0c41e commit d7d14fc

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

datastructures/linked_lists/__init__.py

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -388,12 +388,42 @@ def has_cycle(self):
388388
return True
389389
return False
390390

391-
def detect_node_with_cycle(self):
391+
def cycle_length(self) -> int:
392+
"""
393+
Determines the length of the cycle in a linked list if it has one. The length of the cycle is the number
394+
of nodes that are 'caught' in the cycle
395+
Returns:
396+
int: length of the cycle or number of nodes in the cycle
397+
"""
398+
if not self.head:
399+
return 0
400+
slow_pointer = fast_pointer = self.head
401+
402+
while fast_pointer and fast_pointer.next:
403+
slow_pointer = slow_pointer.next
404+
fast_pointer = fast_pointer.next.next
405+
406+
# Cycle detected
407+
if slow_pointer is fast_pointer:
408+
length = 1
409+
# Move slow pointer by one step to start counting
410+
slow_pointer = slow_pointer.next
411+
412+
# Continue moving the slow pointer until it meets the fast pointer again
413+
while slow_pointer != fast_pointer:
414+
length += 1
415+
slow_pointer = slow_pointer.next
416+
417+
return length
418+
419+
return 0
420+
421+
def detect_node_with_cycle(self) -> Optional[Node]:
392422
"""
393423
Detects the node with a cycle and returns it
394424
"""
395425
if not self.has_cycle():
396-
return False
426+
return None
397427
else:
398428
slow_pointer = fast_pointer = self.head
399429

0 commit comments

Comments
 (0)