Flatten a Multilevel Doubly Linked List

medium linked list dfs doubly linked list

Problem

Flatten a doubly linked list where each node has next, prev, and an optional child pointer into a single-level doubly linked list. Children are spliced in immediately after their parent. All child pointers are nulled out.

Input1 ↔ 2 ↔ 3; 2.child → 4 ↔ 5
Output1 ↔ 2 ↔ 4 ↔ 5 ↔ 3
Walk DFS-style: emit each node, dive into child before continuing along next.

def flatten(head):
    if not head: return None
    stack, prev = [head], None
    while stack:
        cur = stack.pop()
        if prev:
            prev.next = cur
            cur.prev = prev
        if cur.next: stack.append(cur.next)
        if cur.child:
            stack.append(cur.child)
            cur.child = None
        prev = cur
    return head
function flatten(head) {
  if (!head) return null;
  const stack = [head];
  let prev = null;
  while (stack.length) {
    const cur = stack.pop();
    if (prev) { prev.next = cur; cur.prev = prev; }
    if (cur.next) stack.push(cur.next);
    if (cur.child) { stack.push(cur.child); cur.child = null; }
    prev = cur;
  }
  return head;
}
class Solution {
    public Node flatten(Node head) {
        if (head == null) return null;
        Deque<Node> stack = new ArrayDeque<>();
        stack.push(head);
        Node prev = null;
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            if (prev != null) { prev.next = cur; cur.prev = prev; }
            if (cur.next != null) stack.push(cur.next);
            if (cur.child != null) { stack.push(cur.child); cur.child = null; }
            prev = cur;
        }
        return head;
    }
}
Node* flatten(Node* head) {
    if (!head) return nullptr;
    stack<Node*> st;
    st.push(head);
    Node* prev = nullptr;
    while (!st.empty()) {
        Node* cur = st.top(); st.pop();
        if (prev) { prev->next = cur; cur->prev = prev; }
        if (cur->next) st.push(cur->next);
        if (cur->child) { st.push(cur->child); cur->child = nullptr; }
        prev = cur;
    }
    return head;
}
Time: O(n) Space: O(n)