Print nodes of linked list at given indexes - GeeksforGeeks

15 Sep, 2021
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.
Examples: 
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:  
C++
Java
Python3
C#
Javascript
// C++ program to print second linked list// according to data in the first linked list#include <iostream>using namespace std; // Linked List Nodestruct Node {    int data;    struct Node* next;}; /* Function to insert a node at the beginning */void push(struct Node** head_ref, int new_data){    Node* new_node = new Node;     new_node->data = new_data;    new_node->next = (*head_ref);    (*head_ref) = new_node;} // Function to print the second list according// to the positions referred by the 1st listvoid printSecondList(Node* l1, Node* l2){    struct Node* temp = l1;    struct Node* temp1 = l2;     // While first linked list is not null.    while (temp != NULL) {        int i = 1;         // While second linked list is not equal        // to the data in the node of the        // first linked list.        while (i < temp->data) {            // Keep incrementing second list            temp1 = temp1->next;            i++;        }         // Print the node at position in second list        // pointed by current element of first list        cout << temp1->data << " ";         // Increment first linked list        temp = temp->next;         // Set temp1 to the start of the        // second linked list        temp1 = l2;    }} // Driver Codeint main(){    struct Node *l1 = NULL, *l2 = NULL;     // Creating 1st list    // 2 -> 5    push(&l1, 5);    push(&l1, 2);     // Creating 2nd list    // 4 -> 5 -> 6 -> 7 -> 8    push(&l2, 8);    push(&l2, 7);    push(&l2, 6);    push(&l2, 5);    push(&l2, 4);     printSecondList(l1, l2);     return 0;}
// Java program to print second linked list// according to data in the first linked listclass GFG{     // Linked List Nodestatic class Node{    int data;    Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){    Node new_node = new Node();     new_node.data = new_data;    new_node.next = (head_ref);    (head_ref) = new_node;    return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){    Node temp = l1;    Node temp1 = l2;     // While first linked list is not null.    while (temp != null)    {        int i = 1;         // While second linked list is not equal        // to the data in the node of the        // first linked list.        while (i < temp.data)        {            // Keep incrementing second list            temp1 = temp1.next;            i++;        }         // Print the node at position in second list        // pointed by current element of first list        System.out.print( temp1.data + " ");         // Increment first linked list        temp = temp.next;         // Set temp1 to the start of the        // second linked list        temp1 = l2;    }} // Driver Codepublic static void main(String args[]){    Node l1 = null, l2 = null;     // Creating 1st list    // 2 . 5    l1 = push(l1, 5);    l1 = push(l1, 2);     // Creating 2nd list    // 4 . 5 . 6 . 7 . 8    l2 = push(l2, 8);    l2 = push(l2, 7);    l2 = push(l2, 6);    l2 = push(l2, 5);    l2 = push(l2, 4);     printSecondList(l1, l2);}} // This code is contributed by Arnab Kundu
# Python3 program to prsecond linked list# according to data in the first linked list # Linked List Nodeclass new_Node:             # Constructor to initialize the node object    def __init__(self, data):        self.data = data        self.next = None ''' Function to insert a node at the beginning '''def push(head_ref, new_data):    new_node = new_Node(new_data)    new_node.next = head_ref    head_ref = new_node    return head_ref     # Function to print second list according# to the positions referred by the 1st listdef printSecondList(l1,l2):         temp = l1    temp1 = l2         # While first linked list is not None.    while (temp != None):        i = 1                 # While second linked list is not equal        # to the data in the node of the        # first linked list.        while (i < temp.data):            # Keep incrementing second list            temp1 = temp1.next            i += 1                     # Print node at position in second list        # pointed by current element of first list        print(temp1.data,end=" ")                 # Increment first linked list        temp = temp.next                 # Set temp1 to the start of the        # second linked list        temp1 = l2 # Driver Codel1 = Nonel2 = None # Creating 1st list# 2 . 5l1 = push(l1, 5)l1 = push(l1, 2) # Creating 2nd list# 4 . 5 . 6 . 7 . 8l2 = push(l2, 8)l2 = push(l2, 7)l2 = push(l2, 6)l2 = push(l2, 5)l2 = push(l2, 4) printSecondList(l1, l2) # This code is contributed by shubhamsingh10
// C# program to print second linked list// according to data in the first linked listusing System; class GFG{     // Linked List Nodepublic class Node{    public int data;    public Node next;}; /* Function to insert a node at the beginning */static Node push( Node head_ref, int new_data){    Node new_node = new Node();     new_node.data = new_data;    new_node.next = (head_ref);    (head_ref) = new_node;    return head_ref;} // Function to print the second list according// to the positions referred by the 1st liststatic void printSecondList(Node l1, Node l2){    Node temp = l1;    Node temp1 = l2;     // While first linked list is not null.    while (temp != null)    {        int i = 1;         // While second linked list is not equal        // to the data in the node of the        // first linked list.        while (i < temp.data)        {            // Keep incrementing second list            temp1 = temp1.next;            i++;        }         // Print the node at position in second list        // pointed by current element of first list        Console.Write( temp1.data + " ");         // Increment first linked list        temp = temp.next;         // Set temp1 to the start of the        // second linked list        temp1 = l2;    }} // Driver Codepublic static void Main(){    Node l1 = null, l2 = null;     // Creating 1st list    // 2 . 5    l1 = push(l1, 5);    l1 = push(l1, 2);     // Creating 2nd list    // 4 . 5 . 6 . 7 . 8    l2 = push(l2, 8);    l2 = push(l2, 7);    l2 = push(l2, 6);    l2 = push(l2, 5);    l2 = push(l2, 4);     printSecondList(l1, l2);}} // This code has been contributed by 29AjayKumar
<script> // JavaScript program to print second linked list// according to data in the first linked list class Node{    constructor()    {        this.data=0;        this.next=null;    }} /* Function to insert a node at the beginning */function push(head_ref, new_data){    let new_node = new Node();       new_node.data = new_data;    new_node.next = (head_ref);    (head_ref) = new_node;    return head_ref;} // Function to print the second list according// to the positions referred by the 1st listfunction printSecondList(l1,l2){    let temp = l1;    let temp1 = l2;       // While first linked list is not null.    while (temp != null)    {        let i = 1;           // While second linked list is not equal        // to the data in the node of the        // first linked list.        while (i < temp.data)        {            // Keep incrementing second list            temp1 = temp1.next;            i++;        }           // Print the node at position in second list        // pointed by current element of first list        document.write( temp1.data + " ");           // Increment first linked list        temp = temp.next;           // Set temp1 to the start of the        // second linked list        temp1 = l2;    }} // Driver Codelet l1 = null, l2 = null;   // Creating 1st list// 2 . 5l1 = push(l1, 5);l1 = push(l1, 2); // Creating 2nd list// 4 . 5 . 6 . 7 . 8l2 = push(l2, 8);l2 = push(l2, 7);l2 = push(l2, 6);l2 = push(l2, 5);l2 = push(l2, 4); printSecondList(l1, l2); // This code is contributed by avanitrachhadiya2155 </script>
5 8
 
andrew1234
29AjayKumar
SHUBHAMSINGH10
Akanksha_Rai
avanitrachhadiya2155
khushboogoyal499
Traversal
Linked List
Linked List
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Priority Queue using Linked List
Circular Singly Linked List | Insertion
Real-time application of Data Structures
Insertion Sort for Singly Linked List