Given a linked list containing n head nodes where every node in the linked list contains two pointers:
next points to the next node in the list.
bottom pointer to a sub-linked list where the current node is the head. Each of the sub-linked lists nodes and the head
nodes are sorted in ascending order based on their data .We need to flatten the linked list so that all the nodes appear in a single level while maintaining the sorted order.
[Approach 1] Using Sorting - O(n * m * log(n * m)) Time and O(n*m) Space
The idea is to traverse the linked list and push values of all the nodes in an array. Now, we can sort the array in ascending order, and create a new linked list by traversing the sorted array.
Follow the steps to solve the problem:
Traverse the entire linked list using:
Outer loop → move along the next pointer.
Inner loop → move along the bottom pointer.
Push every node's data into the array.
After traversal, sort the array in ascending order.
Now, create a new linked list using the sorted array:
Return the bottom of the dummy node — this is the head of the flattened, sorted list.