#430

Flatten a Multilevel Doubly Linked List

Medium Doubly linked list splicing

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

A doubly linked list's nodes may have a child pointer to another doubly linked list (which may have children too). Flatten everything into one level, placing each child list right after its parent node.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: splice every child list in right after its parent node.

Why this works: on a node with a child, link node ⇄ child, find the child list's tail, link tail ⇄ old next, and clear the child pointer.

Example: 1 ⇄ 2 ⇄ 3, where 2 has child 7 ⇄ 8

1 ⇄ 2 ⇄ 7 ⇄ 8 ⇄ 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the prev pointers or leaving child non-null — the judge checks both.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Linked List
🎬 Episodes 40–45: video coming soon