Skip to content

# Merge two unsorted linked lists to get a sorted list – Set 2

• Difficulty Level : Easy
• Last Updated : 30 Nov, 2021

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â†’9

Input: 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:

Below is an implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `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 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`

Output

`1->2->3->4->5->6->9`

Time Complexity: O((N+M)*log(N+M))
Auxiliary Space: O(N+M)

My Personal Notes arrow_drop_up
Recommended Articles
Page :