Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaJava Program to Merge Two Sorted Linked Lists in New List

Java Program to Merge Two Sorted Linked Lists in New List

We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. 

Input
List 1 : 1-> 3-> 4-> 9->10
List 2 : 2-> 5-> 6-> 9

Output
New List : 1-> 2-> 3-> 4-> 5-> 6-> 9-> 9-> 10

We have two approaches to solve this problem:

  1. Iterative
  2. Recursive

Method 1: Iterative Approach

  • The idea behind this approach is we will take one extra node in the new list which is the Head node of the list.
  • We will take one variable of the type list which is always at the last node of the list so that the appending of a new node becomes easier.
  • We will iterate the loop and check for the smaller element from both lists and append that node to the resultant list.
  • If we reached the end of any list then we will simply append the remaining nodes from the second list.

Implementation:

Java




// Java Program to Merge Two Sorted
// Linked Lists in New List
// Iteratively
 
import java.io.*;
 
public class ListNode {
 
    int val;
    ListNode next;
 
    ListNode() {}
    ListNode(int val) { this.val = val; }
 
    ListNode(int val, ListNode next)
    {
        this.val = val;
        this.next = next;
    }
}
 
class GFG {
    public static ListNode mergeTwoLists(ListNode l1,
                                         ListNode l2)
    {
        // New List
        ListNode result = new ListNode(-1);
 
        // variable to point the last node of the list.
        ListNode p = result;
 
        // Iterate the loop
        while (l1 != null && l2 != null) {
            // Find the smaller element and append it to the
            // list.
            if (l1.val <= l2.val) {
                p.next = l1;
                l1 = l1.next;
            }
 
            else {
                p.next = l2;
                l2 = l2.next;
            }
 
            // Update the variable
            p = p.next;
        }
 
        // If anyone list become empty append the remaining
        // list element of other list.
        if (l1 == null) {
            p.next = l2;
        }
 
        else if (l2 == null) {
            p.next = l1;
        }
 
        // Return the resultant list without first extra
        // node
        return result.next;
    }
 
    // A utility function to print linked list
    static void printList(ListNode node)
    {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(3);
        head1.next.next = new ListNode(5);
 
        // 1->3->5 LinkedList created
        ListNode head2 = new ListNode(0);
        head2.next = new ListNode(2);
        head2.next.next = new ListNode(4);
 
        // 0->2->4 LinkedList created
        ListNode mergedhead = mergeTwoLists(head1, head2);
 
        printList(mergedhead);
    }
}


Output

0 1 2 3 4 5 

Time Complexity: O(N)

Auxiliary Space: O(1)

Method 2: Recursive Approach

One can solve this problem by using the recursion approach. 

  • The function will take two sorted lists as an argument.
  • If any list is empty then it simply returns the remaining elements from the other list.
  • Otherwise, it will check for the smaller element from both lists, append the smaller node to the resultant list and recursively call the function for the next node of the list and another list.

Implementation:

Java




// Java Program to Merge Two Sorted
// Linked Lists in New List
// Recursively
 
import java.io.*;
 
public class ListNode {
 
    int val;
    ListNode next;
 
    ListNode() {}
    ListNode(int val) { this.val = val; }
 
    ListNode(int val, ListNode next)
    {
        this.val = val;
        this.next = next;
    }
}
 
class GFG {
 
    public static ListNode mergeTwoLists(ListNode l1,
                                         ListNode l2)
    {
 
        // New List
        ListNode result = null;
 
        // If anyone list is empty then returns the
        // remaining elements of other list
        if (l1 == null) {
            return l2;
        }
        else if (l2 == null) {
            return l1;
        }
 
        // Find the smaller element and recursively call the
        // function with next node
        if (l1.val <= l2.val) {
            result = l1;
            result.next = mergeTwoLists(l1.next, l2);
        }
        else {
            result = l2;
            result.next = mergeTwoLists(l1, l2.next);
        }
 
        // Return the resultant list
        return (result);
    }
    // A utility function to print linked list
    static void printList(ListNode node)
    {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        ListNode head1 = new ListNode(23);
        head1.next = new ListNode(35);
        head1.next.next = new ListNode(65);
 
        // 23->35->65 LinkedList created
        ListNode head2 = new ListNode(43);
        head2.next = new ListNode(59);
        head2.next.next = new ListNode(60);
 
        // 43->59->60 LinkedList created
        ListNode mergedhead = mergeTwoLists(head1, head2);
 
        printList(mergedhead);
    }
}


Output

23 35 43 59 60 65 

Time Complexity: O(N)

Auxiliary Space: O(N) for call stack since using recursion

RELATED ARTICLES

Most Popular

Recent Comments