Use two pointers at different speeds to detect cycles and locate positions
Advance fast by 2 and slow by 1 to detect cycles; use gaps to find middle or Nth-from-end.
Use on linked lists for cycle detection/entry, middle node, or removing Nth from end in one pass.
Floyd's tortoise and hare to detect cycle
def detect_cycle(head):
# Returns entry node if cycle exists, else None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow = slow.next
fast = fast.next
return slow
return None
Move fast twice as fast to find middle
def middle_node(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
Maintain gap N between pointers
def remove_nth_from_end(head, n):
dummy = ListNode(0, head)
slow = fast = dummy
for _ in range(n):
fast = fast.next
while fast and fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next
def template(*args, **kwargs):
# General template placeholder
pass
Traverse each node O(1) times.
Only pointers used.