Create a linked list from two linked lists by choosing max element at each position - GeeksforGeeks

03 Dec, 2021
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped.
Examples: 
Input: list1 = 5 -> 2 -> 3 -> 8 -> NULL list2 = 1 -> 7 -> 4 -> 5 -> NULL Output: 5 -> 7 -> 4 -> 8 -> NULL
Input: list1 = 2 -> 8 -> 9 -> 3 -> NULL list2 = 5 -> 3 -> 6 -> 4 -> NULL Output: 5 -> 8 -> 9 -> 4 -> NULL 
Approach: We traverse both the linked list at the same time and compare node from both the lists. The node which is greater among them, will be added to the new linked list. We do this for each node and then print the nodes of the generated linked list.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Representation of nodestruct Node {    int data;    Node* next;}; // Function to insert node in a linked listvoid insert(Node** root, int item){    Node *ptr, *temp;    temp = new Node;    temp->data = item;    temp->next = NULL;     if (*root == NULL)        *root = temp;    else {        ptr = *root;        while (ptr->next != NULL)            ptr = ptr->next;         ptr->next = temp;    }} // Function to print the// nodes of a linked listvoid display(Node* root){    while (root != NULL) {        cout << root->data << " -> ";        root = root->next;    }    cout << "NULL";} // Function to generate the required// linked list and return its headNode* newList(Node* root1, Node* root2){    Node *ptr1 = root1, *ptr2 = root2;    Node* root = NULL;     // While there are nodes left    while (ptr1 != NULL) {         // Maximum node at current position        int currMax = ((ptr1->data < ptr2->data)                           ? ptr2->data                           : ptr1->data);         // If current node is the first node        // of the newly linked list being        // generated then assign it to the root        if (root == NULL) {            Node* temp = new Node;            temp->data = currMax;            temp->next = NULL;            root = temp;        }         // Else insert the newly        // created node in the end        else {            insert(&root, currMax);        }         // Get to the next nodes        ptr1 = ptr1->next;        ptr2 = ptr2->next;    }     // Return the head of the    // generated linked list    return root;} // Driver codeint main(){    Node *root1 = NULL, *root2 = NULL, *root = NULL;     // First linked list    insert(&root1, 5);    insert(&root1, 2);    insert(&root1, 3);    insert(&root1, 8);     // Second linked list    insert(&root2, 1);    insert(&root2, 7);    insert(&root2, 4);    insert(&root2, 5);     // Generate the new linked list    // and get its head    root = newList(root1, root2);     // Display the nodes of the generated list    display(root);     return 0;}
// Java implementation of the approachimport java.util.*;class GFG{ // Representation of nodestatic class Node{    int data;    Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){    Node ptr, temp;    temp = new Node();    temp.data = item;    temp.next = null;     if (root == null)        root = temp;    else    {        ptr = root;        while (ptr.next != null)            ptr = ptr.next;         ptr.next = temp;    }    return root;} // Function to print the// nodes of a linked liststatic void display(Node root){    while (root != null)    {        System.out.print( root.data + " - > ");        root = root.next;    }    System.out.print("null");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){    Node ptr1 = root1, ptr2 = root2;    Node root = null;     // While there are nodes left    while (ptr1 != null)    {         // Maximum node at current position        int currMax = ((ptr1.data < ptr2.data)                        ? ptr2.data                        : ptr1.data);         // If current node is the first node        // of the newly linked list being        // generated then assign it to the root        if (root == null)        {            Node temp = new Node();            temp.data = currMax;            temp.next = null;            root = temp;        }         // Else insert the newly        // created node in the end        else        {            root = insert(root, currMax);        }         // Get to the next nodes        ptr1 = ptr1.next;        ptr2 = ptr2.next;    }     // Return the head of the    // generated linked list    return root;} // Driver codepublic static void main(String args[]){    Node root1 = null, root2 = null, root = null;     // First linked list    root1 = insert(root1, 5);    root1 = insert(root1, 2);    root1 = insert(root1, 3);    root1 = insert(root1, 8);     // Second linked list    root2 = insert(root2, 1);    root2 = insert(root2, 7);    root2 = insert(root2, 4);    root2 = insert(root2, 5);     // Generate the new linked list    // and get its head    root = newList(root1, root2);     // Display the nodes of the generated list    display(root); }} // This code is contributed by Arnab Kundu
# Python3 implementation of the approachimport math # Representation of nodeclass Node:    def __init__(self, data):        self.data = data        self.next = None # Function to insert node in a linked listdef insert(root, item):    #ptr, *temp    temp = Node(item)    temp.data = item    temp.next = None     if (root == None):        root = temp    else:        ptr = root        while (ptr.next != None):            ptr = ptr.next         ptr.next = temp         return root # Function to print the# nodes of a linked listdef display(root):    while (root != None) :        print(root.data, end = "->")        root = root.next         print("NULL") # Function to generate the required# linked list and return its headdef newList(root1, root2):    ptr1 = root1    ptr2 = root2    root = None     # While there are nodes left    while (ptr1 != None) :         # Maximum node at current position        currMax = ((ptr1.data < ptr2.data) and                     ptr2.data or ptr1.data)         # If current node is the first node        # of the newly linked list being        # generated then assign it to the root        if (root == None):            temp = Node(currMax)            temp.data = currMax            temp.next = None            root = temp                 # Else insert the newly        # created node in the end        else :            root = insert(root, currMax)                 # Get to the next nodes        ptr1 = ptr1.next        ptr2 = ptr2.next         # Return the head of the    # generated linked list    return root # Driver codeif __name__=='__main__':     root1 = None    root2 = None    root = None     # First linked list    root1 = insert(root1, 5)    root1 = insert(root1, 2)    root1 = insert(root1, 3)    root1 = insert(root1, 8)     # Second linked list    root2 = insert(root2, 1)    root2 = insert(root2, 7)    root2 = insert(root2, 4)    root2 = insert(root2, 5)     # Generate the new linked list    # and get its head    root = newList(root1, root2)     # Display the nodes of the generated list    display(root) # This code is contributed by Srathore
// C# implementation of the approachusing System; class GFG{ // Representation of nodepublic class Node{    public int data;    public Node next;}; // Function to insert node in a linked liststatic Node insert(Node root, int item){    Node ptr, temp;    temp = new Node();    temp.data = item;    temp.next = null;     if (root == null)        root = temp;    else    {        ptr = root;        while (ptr.next != null)            ptr = ptr.next;         ptr.next = temp;    }    return root;} // Function to print the// nodes of a linked liststatic void display(Node root){    while (root != null)    {        Console.Write( root.data + " - > ");        root = root.next;    }    Console.Write("null");} // Function to generate the required// linked list and return its headstatic Node newList(Node root1, Node root2){    Node ptr1 = root1, ptr2 = root2;    Node root = null;     // While there are nodes left    while (ptr1 != null)    {         // Maximum node at current position        int currMax = ((ptr1.data < ptr2.data)                        ? ptr2.data                        : ptr1.data);         // If current node is the first node        // of the newly linked list being        // generated then assign it to the root        if (root == null)        {            Node temp = new Node();            temp.data = currMax;            temp.next = null;            root = temp;        }         // Else insert the newly        // created node in the end        else        {            root = insert(root, currMax);        }         // Get to the next nodes        ptr1 = ptr1.next;        ptr2 = ptr2.next;    }     // Return the head of the    // generated linked list    return root;} // Driver codepublic static void Main(String []args){    Node root1 = null, root2 = null, root = null;     // First linked list    root1 = insert(root1, 5);    root1 = insert(root1, 2);    root1 = insert(root1, 3);    root1 = insert(root1, 8);     // Second linked list    root2 = insert(root2, 1);    root2 = insert(root2, 7);    root2 = insert(root2, 4);    root2 = insert(root2, 5);     // Generate the new linked list    // and get its head    root = newList(root1, root2);     // Display the nodes of the generated list    display(root); }} /* This code contributed by PrinciRaj1992 */
<script>// javascript implementation of the approach     // Representation of nodeclass Node {    constructor() {        this.data = 0;        this.next = null;    }}     // Function to insert node in a linked list    function insert( root , item)    {        var ptr, temp;        temp = new Node();        temp.data = item;        temp.next = null;         if (root == null)            root = temp;        else {            ptr = root;            while (ptr.next != null)                ptr = ptr.next;             ptr.next = temp;        }        return root;    }     // Function to print the    // nodes of a linked list    function display( root)    {        while (root != null)        {            document.write(root.data + " - > ");            root = root.next;        }        document.write("null");    }     // Function to generate the required    // linked list and return its head    function newList( root1,  root2) {         ptr1 = root1, ptr2 = root2;         root = null;         // While there are nodes left        while (ptr1 != null) {             // Maximum node at current position            var currMax = ((ptr1.data < ptr2.data) ? ptr2.data : ptr1.data);             // If current node is the first node            // of the newly linked list being            // generated then assign it to the root            if (root == null) {                 temp = new Node();                temp.data = currMax;                temp.next = null;                root = temp;            }             // Else insert the newly            // created node in the end            else {                root = insert(root, currMax);            }             // Get to the next nodes            ptr1 = ptr1.next;            ptr2 = ptr2.next;        }         // Return the head of the        // generated linked list        return root;    }     // Driver code         root1 = null, root2 = null, root = null;         // First linked list        root1 = insert(root1, 5);        root1 = insert(root1, 2);        root1 = insert(root1, 3);        root1 = insert(root1, 8);         // Second linked list        root2 = insert(root2, 1);        root2 = insert(root2, 7);        root2 = insert(root2, 4);        root2 = insert(root2, 5);         // Generate the new linked list        // and get its head        root = newList(root1, root2);         // Display the nodes of the generated list        display(root); // This code is contributed by todaysgaurav.</script>
5 -> 7 -> 4 -> 8 -> NULL
 
andrew1234
princiraj1992
sapnasingh4991
todaysgaurav
simranarora5sos
Traversal
Linked List
Linked List
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Swap nodes in a linked list without swapping data
Delete a node in a Doubly Linked List
Circular Linked List | Set 2 (Traversal)
Insert a node at a specific position in a linked list
Program to implement Singly Linked List in C++ using class
Priority Queue using Linked List
Insertion Sort for Singly Linked List
Real-time application of Data Structures