×

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

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 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.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 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.

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.

Graph Data Structure

A graph is a non-primitive and non-linear data structure. It is a group of (V, E) where V is a set of vertexes, and E is a set of edge....

3 minutes read.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

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.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.