01 · Question
Reorder a list from L0 -> L1 -> ... -> Ln to L0 -> Ln -> L1 -> Ln-1 -> ....
L0 -> L1 -> ... -> Ln
L0 -> Ln -> L1 -> Ln-1 -> ...
02 · Solution
1def reorderList(head: Optional[ListNode]) -> None:2 if not head or not head.next:3 return4 slow = head5 fast = head6 while fast and fast.next:7 slow = slow.next8 fast = fast.next.next9 second = slow.next10 slow.next = None11 prev = None12 while second:13 nxt = second.next14 second.next = prev15 prev = second16 second = nxt17 first = head18 second = prev19 while second:20 tmp1 = first.next21 tmp2 = second.next22 first.next = second23 second.next = tmp124 first = tmp125 second = tmp2