Flatten a multilevel linked list using level order traversal
Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to flatten the list so that all the nodes appear in a single-level linked list. Flatten the list in a way that all nodes at the first level should come first, then nodes of the second level, and so on.
Examples:
Input:
Output: 1->4->6->2->5->7->3->8 Explanation: The multilevel linked list is flattened as it has no child pointers.
Approach:
To flatten a multilevel linked list, start from the top level and process each node sequentially. For each node, if it has a child node, append this child node to the end of the current list. Continue this process for every node, updating the end of the list accordingly, until all nodes are processed and the list is flattened.
Step by step implementation:
Initialize curr and tail pointer points to head node initially.
Start traversing from the first level and set the tail to the last node.
Start traversing from curr horizontally until curr is not NULL:
If curr->child is not equal to NULL, then append the child list to the end of the resultant list by using tail->next = curr->child. Traverse the child list horizontally , and set tail to the last node of the child list. Set curr->child = NULL to remove the link.
Move the curr pointer to the next node in the list.
Return the head node.
Following is the implementation of the above algorithm.
C++
// C++ Program to flatten list with // next and child pointers #include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node*child;Node(intx){data=x;next=nullptr;child=nullptr;}};// function that flattens // a multilevel linked listvoidflattenList(Node*head){// Base caseif(head==nullptr)return;// Find tail node of first levelNode*tail=head;while(tail->next!=nullptr)tail=tail->next;// One by one traverse through all nodes of first level // linked list till we reach the tail node Node*curr=head;while(curr!=nullptr){// If current node has a child if(curr->child){// then append the child at the end of current list tail->next=curr->child;// and update the tail to new last node Node*tmp=curr->child;while(tmp->next)tmp=tmp->next;tail=tmp;// Remove link between curr and child nodecurr->child=nullptr;}// Change current node curr=curr->next;}}voidprintList(Node*head){Node*curr=head;while(curr!=NULL){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){//Linked List - // 1 -> 2 -> 3// | | // 4 -> 5 6// |// 7Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->child=newNode(4);head->child->next=newNode(5);head->next->next->child=newNode(6);head->child->child=newNode(7);flattenList(head);printList(head);return0;}
C
// C Program to flatten list with // next and child pointers#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;structNode*child;};// function that flattens // a multilevel linked listvoidflattenList(structNode*head){// Base caseif(head==NULL)return;// Find tail node of first levelstructNode*tail=head;while(tail->next!=NULL)tail=tail->next;// One by one traverse through all nodes of first level // linked list till we reach the tail nodestructNode*curr=head;while(curr!=NULL){// If current node has a childif(curr->child){// then append the child at the end of current listtail->next=curr->child;// and update the tail to new last nodestructNode*tmp=curr->child;while(tmp->next)tmp=tmp->next;tail=tmp;// Remove link between curr and child nodecurr->child=NULL;}// Change current nodecurr=curr->next;}}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=new_node->child=NULL;returnnew_node;}intmain(){//Linked List - // 1 -> 2 -> 3// | | // 4 -> 5 6// |// 7structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->child=createNode(4);head->child->next=createNode(5);head->next->next->child=createNode(6);head->child->child=createNode(7);flattenList(head);printList(head);return0;}
Java
// Java Program to flatten list with // next and child pointersclassNode{intdata;Nodenext,child;Node(intx){data=x;next=null;child=null;}}publicclassGfG{// function that flattens // a multilevel linked liststaticvoidflattenList(Nodehead){// Base caseif(head==null)return;// Find tail node of first levelNodetail=head;while(tail.next!=null)tail=tail.next;// One by one traverse through all nodes of first level Nodecurr=head;while(curr!=null){// If current node has a childif(curr.child!=null){// then append the child at the end of current listtail.next=curr.child;// and update the tail to new last nodeNodetmp=curr.child;while(tmp.next!=null)tmp=tmp.next;tail=tmp;// Remove link between curr and child nodecurr.child=null;}// Change current nodecurr=curr.next;}}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){//Linked List - // 1 -> 2 -> 3// | | // 4 -> 5 6// |// 7Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.child=newNode(4);head.child.next=newNode(5);head.next.next.child=newNode(6);head.child.child=newNode(7);flattenList(head);printList(head);}}
Python
# Python Program to flatten list with # next and child pointersclassNode:def__init__(self,new_value):self.data=new_valueself.next=Noneself.child=None# function that flattens # a multilevel linked listdefflatten_list(head):# Base caseifheadisNone:return# Find tail node of first leveltail=headwhiletail.nextisnotNone:tail=tail.next# traverse through all nodes of first level curr=headwhilecurr!=None:# If current node has a childifcurr.childisnotNone:# then append the child at the end of current listtail.next=curr.child# and update the tail to new last nodetmp=curr.childwhiletmp.nextisnotNone:tmp=tmp.nexttail=tmp# Remove link between curr and child nodecurr.child=None# Change current nodecurr=curr.nextdefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":#Linked List - # 1 -> 2 -> 3# | | # 4 -> 5 6# |# 7head=Node(1)head.next=Node(2)head.next.next=Node(3)head.child=Node(4)head.child.next=Node(5)head.next.next.child=Node(6)head.child.child=Node(7)flatten_list(head)print_list(head)
C#
// C# Program to flatten list with // next and child pointersusingSystem;classNode{publicintdata;publicNodenext,child;publicNode(intx){data=x;next=null;child=null;}}classGfG{// function that flattens // a multilevel linked liststaticvoidFlattenList(Nodehead){// Base caseif(head==null)return;// Find tail node of first levelNodetail=head;while(tail.next!=null)tail=tail.next;// traverse through all nodes of first level Nodecurr=head;while(curr!=null){// If current node has a childif(curr.child!=null){// then append the child at the end of current listtail.next=curr.child;// and update the tail to new last nodeNodetmp=curr.child;while(tmp.next!=null)tmp=tmp.next;tail=tmp;// Remove link between curr and child nodecurr.child=null;}// Change current nodecurr=curr.next;}}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){//Linked List - // 1 -> 2 -> 3// | | // 4 -> 5 6// |// 7Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.child=newNode(4);head.child.next=newNode(5);head.next.next.child=newNode(6);head.child.child=newNode(7);FlattenList(head);PrintList(head);}}
JavaScript
// JavaScript Program to flatten list with // next and child pointersclassNode{constructor(new_value){this.data=new_value;this.next=null;this.child=null;}}// function that flattens // a multilevel linked listfunctionflattenList(head){// Base caseif(head===null)return;// Find tail node of first levellettail=head;while(tail.next!==null)tail=tail.next;// traverse through all nodes of first level letcurr=head;while(curr!==null){// If current node has a childif(curr.child!==null){// then append the child at the end of current listtail.next=curr.child;// and update the tail to new last nodelettmp=curr.child;while(tmp.next!==null)tmp=tmp.next;tail=tmp;// Remove link between curr and child nodecurr.child=null;}// Change current nodecurr=curr.next;}}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data);curr=curr.next;}}//Linked List - // 1 -> 2 -> 3// | | // 4 -> 5 6// |// 7lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.child=newNode(4);head.child.next=newNode(5);head.next.next.child=newNode(6);head.child.child=newNode(7);flattenList(head);printList(head);
Output
1 2 3 4 5 6 7
Time Complexity: O(n), where n is the number of nodes in the list. Auxiliary Space: O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.