PracticeNeetCode ↗LeetCode ↗
Given the head of a singly linked list, reorder it in place to interleave the first half with the reversed second half: L0 → Ln → L1 → Ln-1 → L2 → … You must do this by rewiring nodes, not by swapping values.
next to None to terminate the list cleanly.Time: O(n) — Space: O(1)
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head: ListNode) -> None:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
second = slow.next
slow.next = None
prev = None
while second:
nxt = second.next
second.next = prev
prev = second
second = nxt
second = prev
first = head
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first, second = tmp1, tmp2How the solution above works, piece by piece.
slow moves 1 step and fast 2 steps; when fast reaches the end, slow is at the middle.second = slow.next, then slow.next = None splits the list in two. The second half is reversed with the usual prev/curr loop.first.next and second.next in tmp1, tmp2, link first → second → tmp1, then advance both.second has nodes. The first half is never shorter than the second, so once second runs out, the first half's remaining nodes are already linked in order.Running it on head = [1, 2, 3, 4]: