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.
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- Merge a linked list into another linked list at alternate positions
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Length of longest palindrome list in a linked list using O(1) extra space
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Linked List | Set 1 (Introduction)
- Can we reverse a linked list in less than O(n)?
- Linked List Pair Sum
- Rotate a Linked List
Improved By : kaviarasu