The user wants a program that implements a multi-level doubly linked list.
First, I need to understand what a "multi-level doubly linked list" is.
Usually, this refers to a structure where each node has prev, next, and child pointers. The child pointer points to another doubly linked list.
This is often the structure used in problems like LeetCode 430 "Flatten a Multilevel Doubly Linked List".
What features should this program include?
Node Definition: A class or struct for the node containing val, prev, next, and child.
List Management: A class or set of functions to manage the list (insertion, deletion, printing).
Specific Multi-level Logic: A function to flatten the list or to navigate through the levels.
Main Driver: Code to demonstrate the functionality (creating the structure, printing it).
Let's choose Python for this because it's concise and easy to read, though C++ or Java would work too. Python is generally more accessible for algorithmic concepts unless performance is critical. I'll stick with Python.
Step 1: Define the Node
python
class Node:
def __init__(self, val, prev=None, next=None, child=None):
self.val = val
self.prev = prev
self.next = next
self.child = child
Step 2: Core Functionality - Flattening
The most interesting operation on this data structure is "flattening" it into a single-level doubly linked list.
Algorithm for Flatten:
Iterate through the list starting from head.
If a node has a child:
Save the next node (let's call it next_node).
Recursively flatten the child list.
Insert the flattened child list between the current node and next_node.
Move current to the end of the inserted child list.
If no child, move to next.
Wait, a simpler iterative approach for flattening:
Use a stack or simply wire the pointers.
Standard "Depth First Search" approach:
Scan nodes.
If child exists:
If next exists, push next to a stack (or just wire it later).
Actually, pointer wiring is better for O(1) space (if we consider recursion stack separate) or just simple iterative pointer manipulation.
Let's do the pointer wiring approach:
curr.next becomes the child list.
Traverse to end of child list.
Connect end of child to the original curr.next.
Let's stick to a recursive flatten approach for clarity, or an iterative one using a stack.
Actually, let's provide a class that handles insertion and flattening.
Step 3: Program Structure
I will create a MultiLevelDLL class.
Methods:
create_node(val)
append(head, val) (standard DLL)
set_child(parent, child_head) (to build the structure)
flatten(head) (the main logic)
print_list(head) (to visualize)
Let's refine the Flatten logic (iterative stack method is often preferred to avoid recursion depth issues, but recursion is easier to write).
Let's write the recursive flatten logic mentally:
python
def flatten(head):
if not head: return None
current = head
while current:
if current.child:
# Flatten the child list
child_head = flatten(current.child)
next_node = current.next
# Connect current to child
current.next = child_head
child_head.prev = current
current.child = None # Clear child pointer
# Find tail of child list
temp = child_head
while temp.next:
temp = temp.next
# Connect tail of child to next_node
temp.next = next_node
if next_node:
next_node.prev = temp
# Move current to the end of the newly attached list (or just continue)
current = temp # Optimization to avoid re-scanning child
if current:
current = current.next
return head
Actually, the recursive approach can be tricky because flatten(child) returns the head, but we need the logic to handle the wiring inside the main loop.
The standard efficient approach is modifying pointers in place.
Let's write the full Python code.
I will include:
Node class.
Helper functions to create a specific example list (multi-level).
A flatten function (depth-wise modification).
A print_list function to verify.
Example Data Structure to build:
1 --- 2 --- 3 --- 4 --- 5
|
6 --- 7 --- 8
|
9 --- 10
Step 4: Implementation Details
I'll provide a Python script.
I will define a class Node.
I will define functions:
create_multi_level_list(): Hardcodes the structure above.
flatten(head): The algorithm.
print_list(head): Visualization.
Let's double check the iterative flatten algorithm without a stack (O(1) space excluding output list).
python
cur = head
while cur:
if cur.child:
nxt = cur.next
child = cur.child
cur.next = child
child.prev = cur
cur.child = None
# find tail of child
while child.next:
child = child.next
# connect tail to nxt
child.next = nxt
if nxt:
nxt.prev = child
# move cur to child tail to continue processing?
# No, simply continue from cur.next (which is the child head).
# The inner child list might have its own children.
# The standard O(N) approach re-scans the child list if done naively.
# To do it efficiently in one pass, simply just link and continue.
# The while loop will eventually hit the nodes inside the child list and process their children.
cur = cur.next
Yes, this works. By linking cur directly to child, the outer while cur loop will eventually reach the nodes inside the child list in the next iterations, handling nested children naturally.
I will implement this specific logic.
Code Structure:
class Node
def flatten(head)
def print_list(head)
def build_example_list() - to demonstrate.
if __name__ == "__main__":
I will add comments explaining the logic.
I will ensure the code handles empty lists or lists with no children.
Is there anything else "multi-level" could mean?
Sometimes in database contexts, it implies adjacency lists. But in the context of "Doubly Linked List", it almost certainly refers to the structure found in the LeetCode problem (Node with prev, next, child). I will proceed with this assumption and explicitly state it.
Let's refine the example construction to be clear.
Head: 1->2->3
3 has child 7->8
7 has child 11->12
Level 1: 1 2 3 4 5 6
Level 2 (child of 3): 7 8 9 10
Level 3 (child of 8): 11 12
This makes the visualization easier.
Let's write the solution.
Summary of components:
Node Class: Definition with val, prev, next, child.
Flatten Function: Iterative pointer manipulation.
Helper: To visualize and test.
One nice addition: A method to create a multi-level list from a nested list representation?
Example: [1, [2, [3]], 4]?
Maybe too complex for a basic request. I'll stick to manually wiring nodes for the example.
Final check on the iterative flatten logic:
When cur is at a node with a child:
next_node = cur.next
cur.next = cur.child
cur.child.prev = cur
cur.child = None
Iterate to end of this new segment (let's call it tail).
tail.next = next_node
If next_node, next_node.prev = tail
cur continues to cur.next.
Since cur.next is now the start of the child list, the loop proceeds depth-first automatically. This is clean.
I will structure the output clearly.
python
class Node:
def __init__(self, val, prev=None, next=None, child=None):
self.val = val
self.prev = prev
self.next = next
self.child = child
def flatten(head):
# logic
pass
def print_list(head):
# logic
pass
def main():
# build list
# print original (maybe a hierarchical print is too hard, just flatten and print)
# actually, printing original structure is hard without recursion.
# I will just print the flattened result.
pass
Wait, showing the original structure would be cool.
1 -> 2 -> 3
|
v
4 -> 5
I can make a helper that prints indented levels.
Helper print_multi_level(head, level):
Iterate through list.
Print node with indentation based on level.
If child exists, recurse with level+1.
Move to next.
This makes the demo much better.
Plan:
Define Node.
Implement flatten(head).
Implement print_multi_level(head, level).
Implement print_flat(head).
Main block to assemble and demo.
Let's go.
Here is a complete implementation of a Multi-level Doubly Linked List in Python.
This program defines the data structure, allows you to construct a nested list, prints it hierarchically to visualize the levels, and includes a Flatten algorithm to collapse the structure into a single linear list.
The Concept
A standard Doubly Linked List has prev and next pointers. A Multi-level version adds a child pointer.
Next/Prev: Connects nodes on the same level (siblings).
Child: Connects a node to a separate sub-list (the level below).
Python Implementation
python
How it works
The Node Class: Holds val, prev, next, and the crucial child pointer.
Construction:
We create three separate horizontal lists: [1, 2, 3, 4], [5, 6], and [7, 8].
We attach the list starting at 5 as the child of 2.
We attach the list starting at 7 as the child of 6.
Flattening Logic:
The flatten function iterates through the list.
When it encounters a node with a child, it pauses.
It finds the end (tail) of the child list.
It splices the child list into the main list between the current node and the current node's next.
It repeats this until it reaches the end of the main list.
class Node:
"""
Represents a node in a Multi-level Doubly Linked List.
"""
def __init__(self, val, prev=None, next=None, child=None):
self.val = val
self.prev = prev
self.next = next
self.child = child
def __repr__(self):
return f"Node({self.val})"
class MultiLevelDLL:
"""
Manager class for the list containing utilities to build, print,
and flatten the structure.
"""
@staticmethod
def create_sll(values):
"""
Helper to create a simple linear Singly Linked List from a list of values.
Used to easily construct child lists.
"""
if not values:
return None
head = Node(values[0])
current = head
for val in values[1:]:
new_node = Node(val)
current.next = new_node
new_node.prev = current
current = new_node
return head
@staticmethod
def print_multi_level(head):
"""
Prints the list showing hierarchy via indentation.
"""
print("--- Hierarchical View ---")
if not head:
print("List is empty")
return
def traverse(node, level):
while node:
indent = " " * level
print(f"{indent}[Level {level}] {node.val}")
# If there is a child, recurse deeper
if node.child:
traverse(node.child, level + 1)
node = node.next
traverse(head, 0)
print("-------------------------")
@staticmethod
def flatten(head):
"""
Flattens a multi-level doubly linked list into a single linear list.
Depth-First Search (DFS) approach:
When a child is found, insert the entire child list after the current node.
"""
if not head:
return None
curr = head
while curr:
# If no child, just move to the next node
if not curr.child:
curr = curr.next
continue
# 1. We found a child. Find the tail of the child list.
temp = curr.child
while temp.next:
temp = temp.next
# 2. Connect tail of child list to curr.next
temp.next = curr.next
# 3. Connect curr.next's prev to child tail (if curr.next exists)
if curr.next:
curr.next.prev = temp
# 4. Move child list to curr.next
curr.next = curr.child
curr.child.prev = curr
# 5. Remove child pointer
curr.child = None
# Move to the newly attached node (which was the child)
curr = curr.next
return head
@staticmethod
def print_flat_list(head):
"""
Iterates through the list linearly (after flattening) printing prev/next/child status.
"""
print("--- Flattened View (Linear) ---")
curr = head
while curr:
prev_val = curr.prev.val if curr.prev else "None"
next_val = curr.next.val if curr.next else "None"
child_val = curr.child.val if curr.child else "None"
print(f"Node {curr.val} | Prev: {prev_val} | Next: {next_val} | Child: {child_val}")
curr = curr.next
print("-------------------------------")
# ==========================================
# DRIVER CODE (Demonstration)
# ==========================================
if __name__ == "__main__":
# 1. Construct the structure manually
# Level 0: 1 <-> 2 <-> 3 <-> 4
head = MultiLevelDLL.create_sll([1, 2, 3, 4])
# Level 1 (Child of 2): 5 <-> 6
l1_head = MultiLevelDLL.create_sll([5, 6])
# Level 2 (Child of 6): 7 <-> 8
l2_head = MultiLevelDLL.create_sll([7, 8])
# Connect Level 0 to Level 1
node2 = head.next # Node with val 2
node2.child = l1_head
l1_head.prev = node2 # Optional: Some definitions keep child prev null, but standard DLL usually links back.
# Connect Level 1 to Level 2
node6 = l1_head.next # Node with val 6
node6.child = l2_head
l2_head.prev = node6
print("INITIAL STATE:")
MultiLevelDLL.print_multi_level(head)
print("\nFLATTENING...")
flat_head = MultiLevelDLL.flatten(head)
print("\nFINAL STATE:")
MultiLevelDLL.print_flat_list(flat_head)