Java Program To Merge Two Sorted Lists (In-Place)
Last Updated :
11 Jan, 2022
Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).
Examples:
Input: head1: 5->7->9
head2: 4->6->8
Output: 4->5->6->7->8->9
Explanation: The output list is in sorted order.
Input: head1: 1->3->5->7
head2: 2->4
Output: 1->2->3->4->5->7
Explanation: The output list is in sorted order.
There are different discussed different solutions in post below.
Merge two sorted linked lists
Method 1 (Recursive):
Approach: The recursive solution can be formed, given the linked lists are sorted.
- Compare the head of both linked lists.
- Find the smaller node among the two head nodes. The current element will be the smaller node among two head nodes.
- The rest elements of both lists will appear after that.
- Now run a recursive function with parameters, the next node of the smaller element, and the other head.
- The recursive function will return the next smaller element linked with rest of the sorted element. Now point the next of current element to that, i.e curr_ele->next=recursivefunction()
- Handle some corner cases.
- If both the heads are NULL return null.
- If one head is null return the other.
Java
// Java program to merge two sorted
// linked lists in-place.
class GFG
{
static class Node
{
int data;
Node next;
};
// Function to create newNode in
// a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
System.out.printf("%d ",
node.data);
node = node.next;
}
}
// Merges two given lists in-place.
// This function mainly compares head
// nodes and calls mergeUtil()
static Node merge(Node h1, Node h2)
{
if (h1 == null)
return h2;
if (h2 == null)
return h1;
// start with the linked list
// whose head data is the least
if (h1.data < h2.data)
{
h1.next = merge(h1.next, h2);
return h1;
}
else
{
h2.next = merge(h1, h2.next);
return h2;
}
}
// Driver program
public static void main(String args[])
{
Node head1 = newNode(1);
head1.next = newNode(3);
head1.next.next = newNode(5);
// 1.3.5 LinkedList created
Node head2 = newNode(0);
head2.next = newNode(2);
head2.next.next = newNode(4);
// 0.2.4 LinkedList created
Node mergedhead = merge(head1, head2);
printList(mergedhead);
}
}
// This code is contributed by Arnab Kundu
Output:
0 1 2 3 4 5
Complexity Analysis:
- Time complexity:O(n).
Only one traversal of the linked lists are needed. - Auxiliary Space:O(n).
If the recursive stack space is taken into consideration.
Method 2 (Iterative):
Approach: This approach is very similar to the above recursive approach.
- Traverse the list from start to end.
- If the head node of second list lies in between two nodes of the first list, insert it there and make the next node of second list the head. Continue this until there is no node left in both lists, i.e. both the lists are traversed.
- If the first list has reached end while traversing, point the next node to the head of second list.
Note: Compare both the lists where the list with a smaller head value is the first list.
Java
// Java program to merge two sorted
// linked lists in-place.
class GfG
{
static class Node
{
int data;
Node next;
}
// Function to create newNode in
// a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data +
" ");
node = node.next;
}
}
// Merges two lists with headers as
// h1 and h2. It assumes that h1's
// data is smaller than or equal to
// h2's data.
static Node mergeUtil(Node h1, Node h2)
{
// if only one node in first list
// simply point its head to second
// list
if (h1.next == null)
{
h1.next = h2;
return h1;
}
// Initialize current and next
// pointers of both lists
Node curr1 = h1, next1 = h1.next;
Node curr2 = h2, next2 = h2.next;
while (next1 != null &&
curr2 != null)
{
// if curr2 lies in between curr1
// and next1 then do curr1->curr2->next1
if ((curr2.data) >= (curr1.data) &&
(curr2.data) <= (next1.data))
{
next2 = curr2.next;
curr1.next = curr2;
curr2.next = next1;
// now let curr1 and curr2 to point
// to their immediate next pointers
curr1 = curr2;
curr2 = next2;
}
else
{
// if more nodes in first list
if (next1.next != null)
{
next1 = next1.next;
curr1 = curr1.next;
}
// else point the last node of
// first list to the remaining
// nodes of second list
else
{
next1.next = curr2;
return h1;
}
}
}
return h1;
}
// Merges two given lists in-place.
// This function mainly compares head
// nodes and calls mergeUtil()
static Node merge(Node h1, Node h2)
{
if (h1 == null)
return h2;
if (h2 == null)
return h1;
// start with the linked list
// whose head data is the least
if (h1.data < h2.data)
return mergeUtil(h1, h2);
else
return mergeUtil(h2, h1);
}
// Driver code
public static void main(String[] args)
{
Node head1 = newNode(1);
head1.next = newNode(3);
head1.next.next = newNode(5);
// 1->3->5 LinkedList created
Node head2 = newNode(0);
head2.next = newNode(2);
head2.next.next = newNode(4);
// 0->2->4 LinkedList created
Node mergedhead = merge(head1,
head2);
printList(mergedhead);
}
}
// This code is contributed by prerna saini
Output:
0 1 2 3 4 5
Complexity Analysis:
- Time complexity:O(n).
As only one traversal of the linked lists is needed. - Auxiliary Space:O(1).
As there is no space required.
Please refer complete article on
Merge two sorted lists (in-place) for more details!
Similar Reads
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->
4 min read
Java Program To Merge K Sorted Linked Lists - Set 1 Given K sorted linked lists of size N each, merge them and print the sorted output. Examples:Â Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10->11 Merged lists in a sorted order where every element is greater t
6 min read
Java Program To Merge K Sorted Linked Lists Using Min Heap - Set 2 Given k linked lists each of size n and each list is sorted in non-decreasing order, merge them into a single sorted (non-decreasing order) linked list and print the sorted linked list as output.Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL l
5 min read
Java Program to Merge Two Arrays In Java, merging two arrays is a good programming question. We have given two arrays, and our task is to merge them, and after merging, we need to put the result back into another array. In this article, we are going to discuss different ways we can use to merge two arrays in Java.Let's now see the
5 min read
Java Program to Merge Two Arrays In Java, merging two arrays is a good programming question. We have given two arrays, and our task is to merge them, and after merging, we need to put the result back into another array. In this article, we are going to discuss different ways we can use to merge two arrays in Java.Let's now see the
5 min read
Java Program to Find Average of Two Lists To calculate the average of two lists in Java we first need to combine the two lists into one. we can do this using the addAll() method of the ArrayList class. Once you have combined the lists we can calculate the average by summing up all the elements in the combined list and dividing by the total
2 min read