Flattening of Linked List PythonIf we are given a linked list with each node being a separate linked list and two pointers of the same type:
Every linked list, primary and secondary, should be sorted, and the resulting linked list, which will be a flat linked list, should also be sorted. ExamplesInput: Output: 6 -> 7 -> 9 -> 15 -> 21 -> 25 -> 26 -> 29 -> 30 -> 30 -> 31 -> 51 -> 56 Input: Output: 4 -> 5 -> 8 -> 9 -> 10 -> 15 -> 15 -> 17 -> 21 -> 30 The strategy is to define a function to merge the linked lists. We will merge the lists sequentially using the merge() function, recursively merging the current linked list to the recently flattened list. We will use the sec pointer to connect flattened list nodes. The algorithm of the problem is as follows:
The mentioned technique is implemented as follows: Code Output: The flattened linked list is: 6 7 9 15 21 25 26 29 30 30 31 51 56 Time Complexity: The time complexity of this program is O(n * n * m). Here N is the total number of nodes in the primary linked list, and M represents the number of nodes of a single sub-linked list Auxiliary Space: O(n * m). Since we are merging two linked lists simultaneously,
Since we are using a recursive approach, the space complexity of this approach is O(n * m). The recursive function used in this approach will create a recursive stack. The size of this stack will be equivalent to the total number of nodes present in the given nested linked list, which is n * m. Flattening a Linked List using Priority QueuesThe approach is to create a Min-Heap and place the head node of each linked list into this data structure. Then, using the Extract-min method, obtain the minimum integer from the priority queue and proceed in the linked list using that minimum element. To implement this strategy, we will use the following algorithm:
We will implement this algorithm in Python as follows. Code Output: 30 9 7 6 51 26 21 56 31 30 29 Time Complexity: The time complexity of this approach is O(N * M * log(N)). Here N is the number of nodes in the main or primary linked list, and M represents the number of nodes in a single sub-linked list. Auxiliary Space: The space complexity of this approach is O(N). Here N is the number of nodes present in the main linked list. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India