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

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 -> NULLInput:Â
list1 = 2 -> 8 -> 9 -> 3 -> NULLÂ
list2 = 5 -> 3 -> 6 -> 4 -> NULLÂ
Output: 5 -> 8 -> 9 -> 4 -> NULLÂ
A linked list is a data structure where each element is connected to the next element in the list. In this task, we have two linked lists and we want to create a new linked list by picking the maximum element from each position of the two original linked lists and placing it in the same position in the new linked list.
For example, let’s say we have two linked lists:
List 1: [1, 3, 5, 7]List 2: [2, 4, 6, 8]
To create the new linked list, we compare the first elements of both original linked lists, which are 1 and 2. We pick the maximum of these two, which is 2, and place it in the first position of the new linked list.
Next, we compare the second elements of both original linked lists, which are 3 and 4. We pick the maximum of these two, which is 4, and place it in the second position of the new linked list.
We repeat this process for all elements in both linked lists, until we have gone through all elements in both linked lists.
So, the new linked list would be: [2, 4, 6, 8]
This is how we can create a new linked list by choosing the maximum element at each position from two linked lists.
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++
// 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
// 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
# 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#
// C# implementation of the approachusing System; Â
class GFG { Â
// Representation of node public class Node { Â Â Â Â public int data; Â Â Â Â public Node next; }; Â
// Function to insert node in a linked list static 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 list static 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 head static 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 code public 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 */ |
Javascript
<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
Â
Time complexity: O(n) where n is size of linked list
Space complexity: O(n) where n is size of newly created linked list
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



