InterviewHubPRO
Section Overview
Q41

Question 41 of 100

Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

41%
DSA Patterns (Multi-Lang)•Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

Reorder List.

In Simple Words:

  1. Find middle with fast & slow pointers.
  2. Reverse second half of list.
  3. Merge first half and reversed second half alternately.
  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def reorderList(head: ListNode | None) -> None:
    if not head or not head.next: return
    # 1. Find middle
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    # 2. Reverse second half
    prev, curr = None, slow.next
    slow.next = None
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    # 3. Interleave
    first, second = head, prev
    while second:
        tmp1, tmp2 = first.next, second.next
        first.next = second
        second.next = tmp1
        first, second = tmp1, tmp2