top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Flatten a multilevel linked list?

+1 vote
521 views

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, and so on, to produce a multilevel data structure, as shown in below figure.

enter image description here

You are given the head of the first level of the list. Flatten the list so that all the nodes appear in a single-level linked list. You need to flatten the list in way that all nodes at first level should come first, then nodes of second level, and so on.

posted Apr 21, 2014 by Atul Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The problem clearly say that we need to flatten level by level. The idea of solution is, we start from first level, process all nodes one by one, if a node has a child, then we append the child at the end of list, otherwise we don’t do anything. After the first level is processed, all next level nodes will be appended after first level. Same process is followed for the appended nodes.

  1. Take "current" pointer, which will point to head of the fist level of the list
  2. Take "tail" pointer, which will point to end of the first level of the list
  3. Repeat the below procedure while "current" is not NULL.

    • if current node has a child then
      a. append this new child list to the "tail"

      tail->next = current->child
      

    b. find the last node of new child list and update "tail"

    tmp = current->child;
    while (tmp->next != NULL)
        tmp = tmp->next;
    tail = tmp;
    
    • move to the next node. i.e. current = current->next
answer Apr 21, 2014 by anonymous
...