Writing code for Flattening of a Linked List but unable to accomplish the task

47 Views Asked by At

You are given a linked list containing 'n' 'head' nodes, where every node in the linked list contains two pointers:

(1) ‘next’ which points to the next node in the list

(2) ‘child’ pointer to a linked list where the current node is the head.

Each of these child linked lists is in sorted order and connected by 'child' pointer.

Your task is to flatten this linked such that all nodes appear in a single layer or level in a 'sorted order'.

This is the question I am trying to solve however I am only able flatten the first child list after that my program exits for some reason.enter image description here

This is my current code:-

public class Solution {
    public static Node flattenLinkedList(Node head) {
        //Write your code here
        if(head == null||head.next==null){
            return head;
        }
        Node childptr = head.child;
        Node listptr = head;
        Node temp = listptr.next;
        while(temp!=null){
            // Node next = childptr.child;
            childptr.next = listptr.next;
            listptr.next = childptr;
            listptr = listptr.next;
            
            childptr = childptr.child;
            if(childptr==null){
                childptr = temp.child;
                listptr = temp;
                temp = temp.next;
            }
        }
        return head;
    }
}

enter image description here

This is the output I am getting.

0

There are 0 best solutions below