Create new linked list from two given linked list with greater element at each node 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 data) {
   Node *ptr, *temp;
   temp = new Node;
   temp->data = data;
   temp->next = NULL;
   if (*root == NULL) {
      *root = temp;
   }
   else {
      ptr = *root;
      while (ptr->next != NULL) {
         ptr = ptr->next;
      }
      ptr->next = temp;
   }
}
Node* getNewLinkedList(Node* root1, Node* root2) {
   Node *ptr1 = root1, *ptr2 = root2, *ptr;
   Node *root = NULL, *temp;
   while (ptr1 != NULL) {
      temp = new Node;
      temp->next = NULL;
      if (ptr1->data < ptr2->data) {
         temp->data = ptr2->data;
      }
      else {
         temp->data = ptr1->data;
      }
      if (root == NULL) {
         root = temp;
      }
      else {
         ptr = root;
         while (ptr->next != NULL) {
            ptr = ptr->next;
         }
         ptr->next = temp;
      }
      ptr1 = ptr1->next;
      ptr2 = ptr2->next;
   }
   return root;
}
void printLinkedList(Node* root) {
   while (root != NULL) {
      cout << root->data << "->";
      root = root->next;
   }
   cout << "NULL" << endl;
}
int main() {
   Node *root1 = NULL, *root2 = NULL, *root = NULL;
   insertNewNode(&root1, 1);
   insertNewNode(&root1, 2);
   insertNewNode(&root1, 3);
   insertNewNode(&root1, 4);
   cout << "First Linked List: ";
   printLinkedList(root1);
   insertNewNode(&root2, 0);
   insertNewNode(&root2, 5);
   insertNewNode(&root2, 2);
   insertNewNode(&root2, 6);
   cout << "Second Linked List: ";
   printLinkedList(root2);
   root = getNewLinkedList(root1, root2);
   cout << "New Linked List: ";
   printLinkedList(root);
   return 0;
}

Output

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

First Linked List: 1->2->3->4->NULL
Second Linked List: 0->5->2->6->NULL
New Linked List: 1->5->3->6->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