143. Reorder List
Asked at 13Bloomberg56Amazon55Microsoft47Meta45Google40Apple35tcs42Arista Networks78Snap55Morgan Stanley54TikTok53Infosys30LinkedIn20
Problem
Reorder the list L0→L1→…→Ln in place into L0→Ln→L1→Ln−1→L2→Ln−2→…, relinking nodes rather than changing their values.
Example: 1→2→3→4→5 → 1→5→2→4→3
L0 → Ln → L1 → Ln-1 … = find middle, reverse second half, interleave the halves.
1 2 3 4 5 middle at 3 -> split 1 2 3 | 5 4 (reversed)
merge: 1 5 2 4 3
Complexity: O(n) time, O(1) space.
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
slow = fast = head
while fast.next and fast.next.next:
slow, fast = slow.next, fast.next.next
prev, cur = None, slow.next
slow.next = None
while cur:
cur.next, prev, cur = prev, cur, cur.next
a, b = head, prev
while b:
an, bn = a.next, b.next
a.next, b.next = b, an
a, b = an, bn
h = make_list([1, 2, 3, 4, 5]); Solution().reorderList(h)
assert list_vals(h) == [1, 5, 2, 4, 3]
h = make_list([1, 2, 3, 4]); Solution().reorderList(h)
assert list_vals(h) == [1, 4, 2, 3]
class Solution {
public void reorderList(ListNode head) {
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; }
ListNode prev = null, cur = slow.next;
slow.next = null;
while (cur != null) { ListNode nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; }
ListNode a = head, b = prev;
while (b != null) {
ListNode an = a.next, bn = b.next;
a.next = b; b.next = an;
a = an; b = bn;
}
}
}
func reorderList(head *ListNode) {
slow, fast := head, head
for fast.Next != nil && fast.Next.Next != nil { // find the middle
slow, fast = slow.Next, fast.Next.Next
}
var prev *ListNode // reverse the second half
cur := slow.Next
slow.Next = nil
for cur != nil {
cur.Next, prev, cur = prev, cur, cur.Next
}
for a, b := head, prev; b != nil; { // weave the halves together
an, bn := a.Next, b.Next
a.Next, b.Next = b, an
a, b = an, bn
}
}