Doubly Linked List

Flatten a Multilevel Doubly Linked List

Medium
Solve it on LeetCode ↗

The problem

Nodes have next, prev, and an optional child pointing at another level. Flatten to a single level: each child list splices in right after its parent; child pointers become null.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Walk with a cursor. No child → advance.
  2. 2Child found: locate the child chain’s tail.
  3. 3Splice: cursor.next becomes the child (fix prev), the child’s tail connects to the saved old next (fix prev), null the child pointer.
  4. 4Keep advancing — spliced nodes may hold their own children and get processed naturally.

Key insight

Splicing the child inline and CONTINUING the walk handles arbitrary nesting without recursion — the list itself becomes the DFS stack.

The solution

Watch out for

  • Every splice touches FOUR pointers (two next, two prev) — miss one and the list validator fails.
  • Child pointers must end up null; leaving them set fails the judge even if the order is right.