In this Leetcode Flatten a Multilevel Doubly Linked List problem solution You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

Problem solution in Python.

class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        def helper(head, stack=[]):
            if not head: return head
            node = head
            while node:
                if node.child:
                    if stack.append(
                    temp       = node.child
            = temp
                    temp.prev  = node
                    node.child = None
                elif not and stack:
                    temp = stack.pop()
           = temp
                    temp.prev = node
                node =
            return head
        return helper(head)

Problem solution in Java.

class Solution {
    public Node flatten(Node head) {
        Node refHead = head; 
        while (refHead != null) { 
            Node next =; 
            Node child = flatten(refHead.child); 
            Node childRef = child;
            while (child != null && != null) {
                child =;
            if (childRef != null) {
                refHead.child = null;
       = childRef;
                childRef.prev = refHead;
       = next;
                if (next != null) {
                    next.prev = child;
            refHead = next;
        return head;

Problem solution in C++.

class Solution {
    Node* flatten(Node* head) {
        return head;
    Node *flattenEnd(Node *head)
        if (!head) return head;
        Node *fp = head, *next;
        while (fp)
            next = fp->next;
            if (fp->child)
                Node *end = flattenEnd(fp->child);
                fp->next = fp->child;
                fp->next->prev = fp;
                fp->child = NULL;
                fp = end;
                fp->next = next;
                    next->prev = end;
            if (!next)
            fp = next;

        return fp;