Java Program to Merge Two Sorted Linked Lists in New List
Last Updated :
30 Nov, 2022
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:
- Iterative
- 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);
}
}
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);
}
}
Time Complexity: O(N)
Auxiliary Space: O(N) for call stack since using recursion
Similar Reads
Java Program for Merge Sort for Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let head be the first node of the linked list to be sorted and headRef be
4 min read
Java Program to Convert ArrayList to LinkedList Given an array list, your task is to write a program to convert the given array list to Linked List in Java. Examples: Input: ArrayList: [Geeks, forGeeks, A computer Portal] Output: LinkedList: [Geeks, forGeeks, A computer Portal] Input: ArrayList: [1, 2, 3, 4, 5] Output: LinkedList: [1, 2, 3, 4, 5]
6 min read
Concatenation of two Linked lists Given two linked lists. The task is to concatenate the second list to the end of the first list.Examples:Input: list1: 10 -> 15 -> 4 -> 20, list2: 8 -> 4 -> 2 -> 10Output: 10 -> 15 -> 4 -> 20 -> 8 -> 4 -> 2 -> 10Input: list1: 1 -> 2 -> 3, list2: 4 -> 5
6 min read
LinkedList in Java Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure, which is a linear data structure where the elements are not stored in contiguous locations, and every element is a separate object with a data part and an
12 min read
Introduction to Doubly Linked Lists in Java Doubly linked list is a data structure that has reference to both the previous and next nodes in the list. It provides simplicity to traverse, insert and delete the nodes in both directions in a list. In a doubly linked list, each node contains three data members: data: The data stored in the nodene
11 min read
Join two ArrayLists in Java Given two ArrayLists in Java, the task is to join these ArrayLists. Examples:Input: ArrayList1: [Geeks, For, ForGeeks] , ArrayList2: [GeeksForGeeks, A computer portal] Output: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Input: ArrayList1: [G, e, e, k, s] , ArrayList2: [F, o, r, G, e, e,
1 min read