Given a singly linked list which is sorted in ascending order and another singly linked list which 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 nodes of the first linked list. For example, if the first linked list is 1->2->5 then you have to print the 1st, 2nd and 5th elements of the second linked list.
Input: l1 = 1->2->5 l2 = 1->8->7->6->2->9->10 Output : 1->8->2 Elements in l1 are 1, 2 and 5. Therefore, print 1st, 2nd and 5th elements of l2, Which are 1, 8 and 2. Input: l1 = 2->5 l2 = 7->5->3->2->8 Output: 5->8
Take two pointers to traverse the two linked lists using two nested loops. The outer loop points to the elements of the first list and the inner loop point to the elements of the second list respectively. In the first iteration of outer loop, the pointer to the head of the first linked list points to its root node. We traverse the second linked list until we reach the position pointed out by the node’s data in the first linked list. Once the required position is reached, print the data of the second list and repeat this process again until we reach the end of the first linked list.
Below is the implementation of the above approach:
- Print alternate nodes of a linked list using recursion
- Print the alternate nodes of linked list (Iterative Method)
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Delete N nodes after M nodes of a linked list
- Linked List Sum of Nodes Between 0s
- Find sum of even and odd nodes in a linked list
- Sum of the nodes of a Circular Linked List
- Sum of all odd frequency nodes of the Linked List
- Sum of the nodes of a Singly Linked List
- Sum of all distinct nodes in a linked list
- Find the sum of last n nodes of the given Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.