Given two unsorted Linked Lists, L1 of N nodes and L2 of M nodes, the task is to merge them to get a sorted singly linked list.
Examples:
Input: L1 = 3?5?1, L2 = 6?2?4?9
Output: 1?2?3?4?5?6?9Input: L1 = 1?5?2, L2 = 3?7
Output: 1?2?3?5?7
Note: A Memory Efficient approach that solves this problem in O(1) Auxiliary Space has been approached here,
Approach: The idea is to use an auxiliary array to store the elements of both the linked lists and then sort the array in increasing order. And finally, insert all the elements back into the linked list. Follow the steps below to solve the problem:
- Concatenate the two lists by pointing the next of the tail node of the first list, L1 to the first node of the second list, L2.
- Traverse the linked list, L1, and push all the elements into a vector V.
- Sort the vector, V in increasing order.
- After sorting, insert all the elements back to the list, L1.
Below is an implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Linked list node class Node { public : int data; Node* next; }; // Utility function to append key at // end of linked list void insertNode(Node** head, int x) { Node* ptr = new Node; ptr->data = x; ptr->next = NULL; if (*head == NULL) { *head = ptr; } else { Node* temp; temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = ptr; } } // Utility function to print linkedlist void display(Node** head) { Node* temp; temp = *head; if (temp == NULL) { cout << "NULL \n" ; } else { while (temp != NULL) { cout << temp->data; if (temp->next != NULL) cout << "->" ; temp = temp->next; } } } // Function to merge two linked lists void MergeLinkedlist(Node** head1, Node** head2) { Node* ptr; ptr = *head1; while (ptr->next != NULL) { ptr = ptr->next; } // Join linked list by placing address of // first node of L2 in the last node of L1 ptr->next = *head2; } // Function to merge two unsorted linked // lists to get a sorted list void sortLinkedList(Node** head, Node** head1) { // Function call to merge the two lists MergeLinkedlist(head, head1); // Declare a vector vector< int > V; Node* ptr = *head; // Push all elements into vector while (ptr != NULL) { V.push_back(ptr->data); ptr = ptr->next; } // Sort the vector sort(V.begin(), V.end()); int index = 0; ptr = *head; // Insert elements in the linked // list from the vector while (ptr != NULL) { ptr->data = V[index]; index++; ptr = ptr->next; } // Display the sorted and // merged linked list display(head); } // Driver Code int main() { // Given linked list, L1 Node* head1 = NULL; insertNode(&head1, 3); insertNode(&head1, 5); insertNode(&head1, 1); // Given linked list, L2 Node* head2 = NULL; insertNode(&head2, 6); insertNode(&head2, 2); insertNode(&head2, 4); insertNode(&head2, 9); // Function Call sortLinkedList(&head1, &head2); return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG { // Linked list node static class Node { int data; Node next; }; static Node head1, head2; // Utility function to append key at // end of linked list static Node insertNode(Node head, int x) { Node ptr = new Node(); ptr.data = x; ptr.next = null ; if (head == null ) { head = ptr; } else { Node temp; temp = head; while (temp.next != null ) { temp = temp.next; } temp.next = ptr; } return head; } // Utility function to print linkedlist static void display(Node head) { Node temp; temp = head; if (temp == null ) { System.out.print( "null \n" ); } else { while (temp != null ) { System.out.print(temp.data); if (temp.next != null ) System.out.print( "->" ); temp = temp.next; } } } // Function to merge two linked lists static Node MergeLinkedlist() { Node ptr; ptr = head1; while (ptr.next != null ) { ptr = ptr.next; } // Join linked list by placing address of // first node of L2 in the last node of L1 ptr.next = head2; return head1; } // Function to merge two unsorted linked // lists to get a sorted list static void sortLinkedList() { // Function call to merge the two lists Node head = MergeLinkedlist(); // Declare a vector Vector<Integer> V = new Vector<>(); Node ptr = head; // Push all elements into vector while (ptr != null ) { V.add(ptr.data); ptr = ptr.next; } Collections.sort(V); // Sort the vector ; int index = 0 ; ptr = head; // Insert elements in the linked // list from the vector while (ptr != null ) { ptr.data = V.get(index); index++; ptr = ptr.next; } // Display the sorted and // merged linked list display(head); } // Driver Code public static void main(String[] args) { // Given linked list, L1 head1 = insertNode(head1, 3 ); head1 = insertNode(head1, 5 ); head1 = insertNode(head1, 1 ); // Given linked list, L2 head2 = null ; head2 = insertNode(head2, 6 ); head2 = insertNode(head2, 2 ); head2 = insertNode(head2, 4 ); head2 = insertNode(head2, 9 ); // Function Call sortLinkedList(); } } // This code is contributed by umadevi9616 |
Python3
# Py program for the above approach # Linked list node class Node: def __init__( self , d): self .data = d self . next = None # Utility function to append key at # end of linked list def insertNode(head, x): ptr = Node(x) if (head = = None ): head = ptr else : temp = head while (temp. next ! = None ): temp = temp. next temp. next = ptr return head # Utility function to print linkedlist def display(head): temp = head if (temp = = None ): print ( "None" ) else : while (temp. next ! = None ): print (temp.data,end = "->" ) if (temp. next ! = None ): print (" ",end=" ") temp = temp. next print (temp.data) # Function to merge two linked lists def MergeLinkedlist(head1, head2): ptr = head1 while (ptr. next ! = None ): ptr = ptr. next # Join linked list by placing address of # first node of L2 in the last node of L1 ptr. next = head2 return head1 # Function to merge two unsorted linked # lists to get a sorted list def sortLinkedList(head1, head2): # Function call to merge the two lists head1 = MergeLinkedlist(head1, head2) # Declare a vector V = [] ptr = head1 # Push all elements into vector while (ptr ! = None ): V.append(ptr.data) ptr = ptr. next # Sort the vector V = sorted (V) index = 0 ptr = head1 # Insert elements in the linked # list from the vector while (ptr ! = None ): ptr.data = V[index] index + = 1 ptr = ptr. next # Display the sorted and # merged linked list display(head1) # Driver Code if __name__ = = '__main__' : # Given linked list, L1 head1 = None head1 = insertNode(head1, 3 ) head1 = insertNode(head1, 5 ) head1 = insertNode(head1, 1 ) # Given linked list, L2 head2 = None head2 = insertNode(head2, 6 ) head2 = insertNode(head2, 2 ) head2 = insertNode(head2, 4 ) head2 = insertNode(head2, 9 ) # Function Call sortLinkedList(head1, head2) # This code is contributed by mohit kumar 29. |
C#
// C# program for the above approach using System; using System.Collections.Generic; public class GFG { // Linked list node public class Node { public int data; public Node next; }; static Node head1, head2; // Utility function to append key at // end of linked list static Node insertNode(Node head, int x) { Node ptr = new Node(); ptr.data = x; ptr.next = null ; if (head == null ) { head = ptr; } else { Node temp; temp = head; while (temp.next != null ) { temp = temp.next; } temp.next = ptr; } return head; } // Utility function to print linkedlist static void display(Node head) { Node temp; temp = head; if (temp == null ) { Console.Write( "null \n" ); } else { while (temp != null ) { Console.Write(temp.data); if (temp.next != null ) Console.Write( "->" ); temp = temp.next; } } } // Function to merge two linked lists static Node MergeLinkedlist() { Node ptr; ptr = head1; while (ptr.next != null ) { ptr = ptr.next; } // Join linked list by placing address of // first node of L2 in the last node of L1 ptr.next = head2; return head1; } // Function to merge two unsorted linked // lists to get a sorted list static void sortList() { // Function call to merge the two lists Node head = MergeLinkedlist(); // Declare a vector List< int > V = new List< int >(); Node ptr = head; // Push all elements into vector while (ptr != null ) { V.Add(ptr.data); ptr = ptr.next; } V.Sort(); // Sort the vector ; int index = 0; ptr = head; // Insert elements in the linked // list from the vector while (ptr != null ) { ptr.data = V[index]; index++; ptr = ptr.next; } // Display the sorted and // merged linked list display(head); } // Driver Code public static void Main(String[] args) { // Given linked list, L1 head1 = insertNode(head1, 3); head1 = insertNode(head1, 5); head1 = insertNode(head1, 1); // Given linked list, L2 head2 = null ; head2 = insertNode(head2, 6); head2 = insertNode(head2, 2); head2 = insertNode(head2, 4); head2 = insertNode(head2, 9); // Function Call sortList(); } } // This code is contributed by umadevi9616 |
Javascript
// Javascript program for the above approach // Linked list node class Node { constructor(d) { this .data = d this .next = null } } // Utility function to append key at // end of linked list function insertNode(head, x) { ptr = new Node(x) if (head == null ) { head = ptr } else { temp = head while (temp.next != null ) { temp = temp.next } temp.next = ptr } return head } // Utility function to print linkedlist function display(head) { let temp = head if (temp == null ) { document.write( "null" ) } else { while (temp.next != null ) { document.write(temp.data, end = "->" ) if (temp.next != null ) document.write( "" , end = "" ) temp = temp.next } document.write(temp.data) } } // Function to merge two linked lists function MergeLinkedlist(head1, head2) { let ptr = head1 while (ptr.next != null ) ptr = ptr.next // Join linked list by placing address of // first node of L2 in the last node of L1 ptr.next = head2 return head1 } // Function to merge two unsorted linked // lists to get a sorted list function sortLinkedList(head1, head2) { // Function call to merge the two lists head1 = MergeLinkedlist(head1, head2) // Declare a vector let V = [] let ptr = head1 // Push all elements into vector while (ptr != null ) { V.push(ptr.data) ptr = ptr.next } // Sort the vector V = V.sort((a, b) => a - b) index = 0 ptr = head1 // Insert elements in the linked // list from the vector while (ptr != null ) { ptr.data = V[index] index += 1 ptr = ptr.next } // Display the sorted and // merged linked list display(head1) } // Driver Code // Given linked list, L1 let head1 = null ; head1 = insertNode(head1, 3) head1 = insertNode(head1, 5) head1 = insertNode(head1, 1) // Given linked list, L2 let head2 = null head2 = insertNode(head2, 6) head2 = insertNode(head2, 2) head2 = insertNode(head2, 4) head2 = insertNode(head2, 9) // Function Call sortLinkedList(head1, head2) // This code is contributed by gfgking |
1->2->3->4->5->6->9
Time Complexity: O((N+M)*log(N+M))
Auxiliary Space: O(N+M)
Another Approach: This code defines a program to merge two unsorted linked lists into a single sorted linked list. The main steps of the program are:
- Define a class called “Node” to represent a node of a linked list. Each node contains an integer value “data” and a pointer “next” to the next node in the list.
- Define a utility function called “insertNode” to insert a new node with a given value at the end of a linked list. This function takes two parameters: a reference to a pointer to the head of the list, and the value to be inserted.
- Define a utility function called “display” to print the elements of a linked list. This function takes a pointer to the head of the list as a parameter and prints the value of each node followed by “->” until the end of the list is reached, and then prints “NULL”.
- Define a function called “MergeLinkedlist” to merge two linked lists. This function takes two parameters: a reference to a pointer to the head of the first list, and a pointer to the head of the second list. It first finds the last node of the first list and sets its “next” pointer to the head of the second list.
- Define a function called “sortLinkedList” to merge two unsorted linked lists into a single sorted linked list. This function takes two parameters: pointers to the heads of the two lists. It first calls “MergeLinkedlist” to merge the two lists into a single linked list. Then it creates a vector and pushes all the elements of the merged list into the vector. It sorts the vector using the “sort” function from the <algorithm> library, and then creates a new linked list by inserting the elements of the sorted vector one by one using the “insertNode” function. Finally, it calls “display” to print the sorted linked list.
- In the main function, two unsorted linked lists are created using “insertNode”. The “sortLinkedList” function is called with these two lists as parameters.
Below is the implementation of the above approach:
C++
#include <iostream> #include <vector> #include <algorithm> using namespace std; // Linked list node class Node { public : int data; Node* next; Node( int val) : data(val), next(nullptr) {} }; // Utility function to append key at // end of linked list void insertNode(Node*& head, int x) { Node* ptr = new Node(x); if (head == nullptr) { head = ptr; } else { Node* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = ptr; } } // Utility function to print linkedlist void display(Node* head) { if (head == nullptr) { cout << "NULL" << endl; } else { while (head != nullptr) { cout << head->data; if (head->next != nullptr) cout << "->" ; head = head->next; } cout << endl; } } // Function to merge two linked lists void MergeLinkedlist(Node*& head1, Node* head2) { Node* ptr = head1; while (ptr->next != nullptr) { ptr = ptr->next; } // Join linked list by placing address of // first node of L2 in the last node of L1 ptr->next = head2; } // Function to merge two unsorted linked // lists to get a sorted list void sortLinkedList(Node* head1, Node* head2) { // Function call to merge the two lists MergeLinkedlist(head1, head2); // Declare a vector vector< int > V; // Push all elements into vector while (head1 != nullptr) { V.push_back(head1->data); head1 = head1->next; } // Sort the vector sort(V.begin(), V.end()); // Insert elements in the linked // list from the vector Node* curr = nullptr; for ( int i = 0; i < V.size(); i++) { if (i == 0) { curr = new Node(V[i]); head1 = curr; } else { curr->next = new Node(V[i]); curr = curr->next; } } // Display the sorted and // merged linked list display(head1); } // Driver Code int main() { // Given linked list, L1 Node* head1 = nullptr; insertNode(head1, 3); insertNode(head1, 5); insertNode(head1, 1); // Given linked list, L2 Node* head2 = nullptr; insertNode(head2, 6); insertNode(head2, 2); insertNode(head2, 4); insertNode(head2, 9); // Function Call sortLinkedList(head1, head2); return 0; } // This code is contributed by rudra1807raj |
Python3
# Linked list node class Node: def __init__( self , val): self .data = val self . next = None # Utility function to append key at # end of linked list def insertNode(head, x): ptr = Node(x) if head is None : head = ptr else : temp = head while temp. next is not None : temp = temp. next temp. next = ptr return head # Utility function to print linkedlist def display(head): if head is None : print ( "NULL" ) else : while head is not None : print (head.data, end = "") if head. next is not None : print ( "->" , end = "") head = head. next print () # Function to merge two linked lists def MergeLinkedlist(head1, head2): ptr = head1 while ptr. next is not None : ptr = ptr. next # Join linked list by placing address of # first node of L2 in the last node of L1 ptr. next = head2 # Function to merge two unsorted linked # lists to get a sorted list def sortLinkedList(head1, head2): # Function call to merge the two lists MergeLinkedlist(head1, head2) # Declare a vector V = [] # Push all elements into vector while head1 is not None : V.append(head1.data) head1 = head1. next # Sort the vector V.sort() # Insert elements in the linked # list from the vector curr = None for i in range ( len (V)): if i = = 0 : curr = Node(V[i]) head1 = curr else : curr. next = Node(V[i]) curr = curr. next # Display the sorted and # merged linked list display(head1) # Driver Code if __name__ = = '__main__' : # Given linked list, L1 head1 = None head1 = insertNode(head1, 3 ) head1 = insertNode(head1, 5 ) head1 = insertNode(head1, 1 ) # Given linked list, L2 head2 = None head2 = insertNode(head2, 6 ) head2 = insertNode(head2, 2 ) head2 = insertNode(head2, 4 ) head2 = insertNode(head2, 9 ) # Function Call sortLinkedList(head1, head2) # This code is contributed by shiv1o43g |
C#
using System; using System.Collections.Generic; using System.Linq; // Linked list node class Node { public int data; public Node next; public Node( int val) { data = val; next = null ; } } class Program { // Utility function to append key at // end of linked list static void insertNode( ref Node head, int x) { Node ptr = new Node(x); if (head == null ) { head = ptr; } else { Node temp = head; while (temp.next != null ) { temp = temp.next; } temp.next = ptr; } } // Utility function to print linkedlist static void display(Node head) { if (head == null ) { Console.WriteLine( "NULL" ); } else { while (head != null ) { Console.Write(head.data); if (head.next != null ) Console.Write( "->" ); head = head.next; } Console.WriteLine(); } } // Function to merge two linked lists static void MergeLinkedlist( ref Node head1, Node head2) { Node ptr = head1; while (ptr.next != null ) { ptr = ptr.next; } // Join linked list by placing address of // first node of L2 in the last node of L1 ptr.next = head2; } // Function to merge two unsorted linked // lists to get a sorted list static void sortLinkedList(Node head1, Node head2) { // Function call to merge the two lists MergeLinkedlist( ref head1, head2); // Declare a list List< int > lst = new List< int >(); // Push all elements into the list while (head1 != null ) { lst.Add(head1.data); head1 = head1.next; } // Sort the list lst.Sort(); // Insert elements in the linked // list from the list Node curr = null ; for ( int i = 0; i < lst.Count; i++) { if (i == 0) { curr = new Node(lst[i]); head1 = curr; } else { curr.next = new Node(lst[i]); curr = curr.next; } } // Display the sorted and // merged linked list display(head1); } // Driver Code static void Main( string [] args) { // Given linked list, L1 Node head1 = null ; insertNode( ref head1, 3); insertNode( ref head1, 5); insertNode( ref head1, 1); // Given linked list, L2 Node head2 = null ; insertNode( ref head2, 6); insertNode( ref head2, 2); insertNode( ref head2, 4); insertNode( ref head2, 9); // Function Call sortLinkedList(head1, head2); Console.ReadLine(); } } //This code is contributed by rudra1807raj |
1->2->3->4->5->6->9
Time Complexity: The time complexity of the given algorithm is O(n log n) where n is the total number of elements in the two linked lists. This is because the algorithm involves sorting the elements using the sort function, which has a time complexity of O(n log n). In addition, iterating over the linked lists to populate the vector and then the sorted linked list takes O(n) time.
Auxiliary Space: The space complexity of the given algorithm is O(n) where n is the total number of elements in the two linked lists. This is because we are creating a vector of size n to store all the elements of the linked list before sorting. In addition, we are creating a new linked list of size n to store the sorted elements. However, we are not using any extra space proportional to the size of the input beyond the two linked lists and the vector used for sorting, so the space complexity is O(n).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!