![]() |
VOOZH | about |
Given head of two singly linked lists, first one is sorted and the other one is unsorted. The task is to print the elements of the second linked list according to the position pointed out by the data in the first linked list. For example, if the first linked list is 1->2->5, then you have to print the second linked list's 1st, 2nd and 5th node's data.
Note: All the position (represented by each node of sorted linked list) will be exist in the unsorted linked list.
Examples:
Input: head1 = 1->2->5, head2 = 1->8->7->6->2->9->10
Output : 1->8->2
Explanation: Elements in head1 are 1, 2 and 5. Therefore, print 1st, 2nd and 5th elements of l2,Which are 1, 8 and 2.Input: head1 = 2->5, head2 = 7->5->3->2->8
Output: 5->8
Table of Content
The idea is to use two nested loops to traverse two linked lists. The outer loop traverses the first list, while the inner loop traverses the second list until a specific position is reached, printing the data at that position.
Step-by-step approach:
Below is the implementation of the above approach:
5 8
Time Complexity:O(n), To traverse the second linked list completely.
Auxiliary Space: O(1)
The idea is to utilize the sorted order of the first list to traverse the second list more efficiently, reducing unnecessary comparisons by skipping irrelevant nodes.
Step-by-step approach:
Below is the implementation of the above approach:
5 8
Time Complexity: O(m+n), At worst case we would traverse each nodes of both linked list
Auxiliary Space: O(1)