×

Merge two sorted linked lists

Merge two sorted linked lists

In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing order, and we need to merge them into one list, which will also be in increasing order.

Example:

Suppose, the first linked list is 3 -> 5 -> 8 and the second linked lists is 2 -> 4 -> 6. Now, we will merge them into one list and the pointer to the head node of the merged list will return 2 -> 3 -> 4 -> 5 -> 6 -> 8.

Using two pointers method

This method will traverse both the linked lists till the end, compare the nodes of both the linked lists, and check which of the node has a larger value. The larger node will be added to the resultant or merged linked list.

Algorithm:

1) First, initialize the resultant linked list as empty: head = NULL.

2) We will take two pointers head1 and head2, as the starting pointer of the first and second linked list.

3) Then, we will traverse both the linked list till the end:

    While (head1 != NULL and head2 != NULL)

    a) After this, we will check which node contains the greater value.

    b) Then, we will add or insert a larger value node in the resultant linked list.

4) If the head2 or second linked list becomes NULL before the first linked list, then we will add all nodes of the first linked list in the resultant linked list.

5) If the head1 or first linked list becomes NULL before the second linked list, then we will add all nodes of the second linked list in the resultant linked list.

Source code to merge two sorted linked lists in Java:

 import java.util.*;
 class Node
 {
     int data;
     Node next;
     Node(int d) {
         data  =  d;
         next  =  null;
     }
 }
 class MergeLists
 {
   /* Function to print linked list */
    public static void printList(Node head)
     {
         System.out.println("The merged linked list is:");
         while (head!= null)
         {
            System.out.print(head.data+" ");
            head  =  head.next;
         } 
         System.out.println();
     }
      /* Driver program to test above functions */
     public static void main(String args[])
     {
          Scanner sc  =  new Scanner(System.in);
          System.out.println("Enter the total no of elements for first linked list:");          
              int n1 = sc.nextInt();
              System.out.println("Enter the total no of elements for second linked list:");
              int n2 = sc.nextInt();
              System.out.println("Enter the elements for first linked list:");
              Node head1 = new Node(sc.nextInt());
             Node tail1  =  head1;
             for(int i = 0; i<n1-1; i++)
             {
                 tail1.next  =  new Node(sc.nextInt());
                 tail1  =  tail1.next;
             }
              System.out.println("Enter the elements for second linked list:");
              Node head2 = new Node(sc.nextInt());
             Node tail2 = head2;
             for(int i = 0; i < n2-1; i++)
             {
                 tail2.next = new Node(sc.nextInt());
                 tail2 = tail2.next;
             }
                                     LinkedList obj  =  new LinkedList();
                                     Node head  =  obj.sortedMerge(head1,head2);
                                     printList(head);                    
     }
 }
 // } Driver Code Ends
 class LinkedList
 {
     //Function to merge two sorted linked lists.
     Node sortedMerge(Node head1, Node head2) {
      Node head = null;
     Node t = null;
     while(head1!=null && head2!=null)
     {
         if(head1.data<=head2.data)
         {
             if(head==null)
             {
                 head = new Node(head1.data);
                 t = head;
             }
             else
             {
                 t.next = new Node(head1.data);
                 t = t.next;
             }
             head1 = head1.next;
         }
         else
         {
             if(head == null)
             {
                 head = new Node(head2.data);
                 t = head;
             }
             else
             {
                 t.next = new Node(head2.data);
                 t = t.next;
             }
             head2 = head2.next;
         }
     }
     while(head1!= null)
     {
         t.next = new Node(head1.data);
         t = t.next;
         head1 = head1.next;
     }
     while(head2 != null)
     {
         t.next = new Node(head2.data);
         t = t.next;
         head2 = head2.next;
     }
     return head;
    }
 } 

Output: -

Merge two sorted linked lists

Related Topics

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

5 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.