Flatten a multilevel linked list in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a multilevel linked list. Our task is to create a program to flatten a multilevel linked list.

The flattening operation is done in such a way that the first level nodes will occur first in the linked list and then the second level nodes will occur.

Multilevel linked list is a multi-dimensional data structure in which every node of the linked list has two link pointers, one a link to the next node and one to the child list with one or more nodes. This child pointer may or may not point to other list nodes.


Let’s take an example to understand the problem



1-> 9-> 8 -> 4 -> 6-> 7-> 2-> 3-> 5

Solution Approach

A simple solution to the problem is by using doing a level order traversal type of algorithm. We will be traversing the linked list starting from the first node and traversing all the nodes at the same level. If any child pointer is present for a node, move it to the end of the current linked list using the tail pointer. Then recursively perform the same traversal for each child node of the linked list. The below program will elaborate the logic better.


Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;

#define SIZE(arr) (sizeof(arr)/sizeof(arr[0]))

class Node{
   int data;
   Node *next;
   Node *child;
Node *createList(int *arr, int n){
   Node *head = NULL;
   Node *p;
   int i;
   for (i = 0; i < n; ++i){
      if (head == NULL)
         head = p = new Node();
         p->next = new Node();
         p = p->next;
      p->data = arr[i];
      p->next = p->child = NULL;
   return head;
Node *createList(void){
   int arr1[] = {1, 9, 8, 4, 6};
   int arr2[] = {7, 3, 2};
   int arr3[] = {5};
   Node *head1 = createList(arr1, (sizeof(arr1)/sizeof(arr1[0])));
   Node *head2 = createList(arr2, (sizeof(arr2)/sizeof(arr2[0])));
   Node *head3 = createList(arr3, (sizeof(arr3)/sizeof(arr3[0])));
   head1->child = head2;
   head1->next->child = head3;
   return head1;
void flattenLinkedList(Node *head){
   if (head == NULL)
   Node *tmp;
   Node *tail = head;
   while (tail->next != NULL)
   tail = tail->next;
   Node *cur = head;
   while (cur != tail){
      if (cur->child){
         tail->next = cur->child;
         tmp = cur->child;
         while (tmp->next)
         tmp = tmp->next;
         tail = tmp;
      cur = cur->next;
int main(void){
   Node *head = NULL;
   head = createList();
   cout<<"The flattened Linked List is ";
   while (head != NULL){
      cout << head->data << " ";
      head = head->next;
   return 0;


The flattened Linked List is 1 9 8 4 6 7 3 2 5
Updated on 31-Jan-2022 12:54:39