Given a linked list where every node represents a linked list and contains two pointers of its type:
(i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
(ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).
All linked lists are sorted. See the following example
5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45
Write a function flatten() to flatten the lists into a single linked list. The flattened linked list should also be sorted. For example, for the above input list, output list should be 5->7->8->10->19->20->22->28->30->35->40->45->50.
The idea is to use Merge() process of merge sort for linked lists. We use merge() to merge lists one by one. We recursively merge() the current list with already flattened list.
The down pointer is used to link nodes of the flattened list.
Following are C and Java implementations.
5 7 8 10 19 20 20 22 30 35 40 45 50
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Merge a linked list into another linked list at alternate positions
- Check if a linked list is Circular Linked List
- Length of longest palindrome list in a linked list using O(1) extra space
- Find the middle of a given linked list in C and Java
- Program for n'th node from the end of a Linked List
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Detect loop in a linked list
- Reverse a linked list
- Function to check if a singly linked list is palindrome
- Clone a linked list with next and random pointer | Set 1
- Given a linked list which is sorted, how will you insert in sorted way
- Print reverse of a Linked List without actually reversing
- Remove duplicates from an unsorted linked list
- Remove duplicates from a sorted linked list
- Pairwise swap elements of a given linked list
- Delete a node in a Doubly Linked List
- Reverse a Linked List in groups of given size | Set 1
- Sorted insert for circular linked list
- Segregate even and odd nodes in a Linked List
- Detect and Remove Loop in a Linked List