Flatten a multilevel linked list

Flatten a list whose nodes can each hang a child list off of them, splicing every child in depth-first so the result is one plain list.

Time O(n)Space O(d)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Walk the main list node by node. A node with a child is hiding a whole extra list underneath it: splice that child in right after the node, reconnect the child's tail to whatever used to come next, and clear the child pointer so the structure is a single flat list again.

Code

public static Node Flatten(Node head) {
    for (Node n = head; n != null; n = n.next) {
        if (n.child == null) continue;
        Node childTail = n.child;
        while (childTail.next != null) childTail = childTail.next;
        childTail.next = n.next;
        n.next = n.child;
        n.child = null;
    }
    return head;
}
static Node flatten(Node head) {
    for (Node n = head; n != null; n = n.next) {
        if (n.child == null) continue;
        Node childTail = n.child;
        while (childTail.next != null) childTail = childTail.next;
        childTail.next = n.next;
        n.next = n.child;
        n.child = null;
    }
    return head;
}
Node* flatten(Node* head) {
    for (Node* n = head; n; n = n->next) {
        if (!n->child) continue;
        Node* childTail = n->child;
        while (childTail->next) childTail = childTail->next;
        childTail->next = n->next;
        n->next = n->child;
        n->child = nullptr;
    }
    return head;
}
def flatten(head: Node | None) -> Node | None:
    n = head
    while n:
        if n.child is None: n = n.next; continue
        child_tail = n.child
        while child_tail.next: child_tail = child_tail.next
        child_tail.next = n.next
        n.next = n.child
        n.child = None
        n = n.next
    return head

Tips

In the .NET library

This demo flattens one child list for clarity; the general solution recurses (or keeps an explicit stack of 'what comes next' addresses) so a child's own child gets flattened too, depth first.