educative.io

Why starting fast pointer from head.next and not head in splitInHalf method?

In the splitInHalf method, we are using 2 pointer technique to find the mid node of the list.
But in this case why are we not starting slow and fast both with head. Instead why are we starting it with head.next. ?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hello Vivek,
We initialize first as head.next because we’ve set our while loop (lines 25–31) in a way that stops slow at the list mid-point.
We can also initialize first as head but we will encounter an error as slow won’t stop at the list mid-point. Try a dry-run with the first pointer initialized as head. A few changes with the while loop will allow us to use first as head. For example:

slow = head
fast = head
while fast.next:
    fast = fast.next
    if not fast.next:
        break
    elif fast:
        fast = fast.next
        slow = slow.next