Flatten a Multilevel Doubly Linked List
Nodes have next, prev and a possible child sublist (itself multilevel). Flatten into one level, children spliced in right after their parent.
Intuition
Depth-first order is exactly the flattened order: node, then its child list, then its former next. A stack remembers the interrupted next while we dive into a child — pop it back when the child branch is exhausted.
Approach
Walk with a stack
At each node: if it has a child, push its next (may be null-skipped) and rewire next to the child. The child pointer is cleared.
Resume on dead ends
When next is null and the stack isn't empty, pop the saved node and splice it after the current node, fixing both directions.
Keep prev consistent
Every rewire sets next.prev too — the doubly-linked invariant is maintained throughout.
Solution & live demo
Edge cases
Nothing to push; the child simply continues the list.
Return null immediately.