Create a linked list from two linked lists by choosing max element at each position in C++ Program


In this tutorial, we are going to write a program that creates a new linked list from the given linked lists.

We have given two linked lists of the same size and we have to create a new linked list from the two linked lists with the max numbers from the two linked lists.

Let's see the steps to solve the problem.

  • Write a struct node.

  • Create two linked lists of the same size.

  • Iterate over the linked list.

    • Find the max number from the two linked lists nodes.

    • Create a new node with the max number.

    • Add the new node to the new linked list.

  • Print the new linked list.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node* next;
};
void insertNewNode(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;
   }
}
void printLinkedList(Node* root) {
   while (root != NULL) {
      cout << root->data << " -> ";
      root = root->next;
   }
   cout << "NULL" << endl;
}
Node* generateNewLinkedList(Node* root1, Node* root2) {
   Node *ptr1 = root1, *ptr2 = root2;
   Node* root = NULL;
   while (ptr1 != NULL) {
      int currentMax = ((ptr1->data < ptr2->data) ? ptr2->data : ptr1->data);
      if (root == NULL) {
         Node* temp = new Node;
         temp->data = currentMax;
         temp->next = NULL;
         root = temp;
      }
      else {
         insertNewNode(&root, currentMax);
      }
      ptr1 = ptr1->next;
      ptr2 = ptr2->next;
   }
   return root;
}
int main() {
   Node *root1 = NULL, *root2 = NULL, *root = NULL;
   insertNewNode(&root1, 1);
   insertNewNode(&root1, 2);
   insertNewNode(&root1, 3);
   insertNewNode(&root1, 4);
   insertNewNode(&root2, 3);
   insertNewNode(&root2, 1);
   insertNewNode(&root2, 2);
   insertNewNode(&root2, 4);
   root = generateNewLinkedList(root1, root2);
   printLinkedList(root);
   return 0;
}

Output

If you run the above code, then you will get the following result.

3 -> 2 -> 3 -> 4 -> NULL

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 28-Jan-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements