VOOZH about

URL: https://www.geeksforgeeks.org/dsa/flatten-a-linked-list-with-next-and-child-pointers/

⇱ Flatten a multilevel linked list using level order traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flatten a multilevel linked list using level order traversal

Last Updated : 3 Oct, 2024

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:

👁 2_5


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. 


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)

Comment
Article Tags:
Article Tags: