Skip to content
Code ReadingFast and Slow
Predict the Output

Fast and Slow

The slow pointer moves one step, the fast one two. Where is slow when the loop stops?
1class Node:
2 def __init__(self, val, nxt=None):
3 self.val, self.next = val, nxt
4
5head = Node(1, Node(2, Node(3, Node(4))))
6slow = fast = head
7while fast and fast.next:
8 slow = slow.next
9 fast = fast.next.next
10print(slow.val)