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.
- Add two numbers represented by linked lists | Set 2
- Merge Sort for Linked Lists
- Flatten a multilevel linked list
- Sort a linked list of 0s, 1s and 2s
- Top 20 Linked List Interview Question
- Merge two sorted linked lists
- Rotate a Linked List
- Write a function to get the intersection point of two Linked Lists.
- Detect and Remove Loop in a Linked List
- Add 1 to a number represented as linked list
- Find the middle of a given linked list in C and Java
- Delete N nodes after M nodes of a linked list
- Reverse a Linked List in groups of given size | Set 1
- Clone a linked list with next and random pointer | Set 1
- Find a triplet from three linked lists with sum equal to a given number
Improved By : kaviarasu