Linked List Zip

LeetCode

LeetCode: https://leetcode.com/problems/reorder-list/

Reorder a list from L0 -> L1 -> ... -> Ln to L0 -> Ln -> L1 -> Ln-1 -> ....

1def reorderList(head: Optional[ListNode]) -> None:
2 if not head or not head.next:
3 return
4 slow = head
5 fast = head
6 while fast and fast.next:
7 slow = slow.next
8 fast = fast.next.next
9 second = slow.next
10 slow.next = None
11 prev = None
12 while second:
13 nxt = second.next
14 second.next = prev
15 prev = second
16 second = nxt
17 first = head
18 second = prev
19 while second:
20 tmp1 = first.next
21 tmp2 = second.next
22 first.next = second
23 second.next = tmp1
24 first = tmp1
25 second = tmp2
1
0
2
1
slow
3
2
4
3
fast
5
4
Step 1 / 3
Step 1:
Find the midpoint with slow/fast pointers.
Pointers: fast=4, slow=2
Focus: select @ [2]