  Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email  Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Merge Two Unsorted Linked Lists To Get A Sorted List

Last Updated on December 14, 2022 by Prepbytes ### Introduction

Even though we have seen different operations on linked lists, where we have done insertion, deletion etc. But what if we want to merge two unsorted linked lists. Lets just see an approach on how to merge 2 unsorted linked lists

### Problem Statement on how to merge two unsorted linked lists

In this problem, we are given two unsorted linked lists, and we have to merge these two linked lists to get a sorted linked list.

Prerequisites: Bubble sort on linked list.

### Problem Statement Understanding merge two unsorted linked lists

Let’s try to understand the problem statement with the help of examples.

Let’s say the given linked lists are :

List1 = head → 1 → 6 → 10 → NULL , List2 = head → 5 → 3 → 9 → NULL • So now, according to the problem statement, the given linked lists List1 and List2 are unsorted, and we need to merge them to get a sorted linked list.
• After merging the linked lists, we need to return the head of the merged linked list.
• After merging the two linked lists in the above example, the sorted linked lists will be head → 1 → 3 → 5 → 6 → 9 → 10 → NULL. The linked list will be sorted in ascending order.

#### Some more Examples

Example 1:

Input:

List1 = head → 4 → 50→ 12 → NULL

List2 = head → 10 →1→ 60 → NULL

Output :

head → 1 → 4 → 10→12 → 50 → 60

Example 2:

Input:

List 1 = head → 10 → 20 → 60 → NULL

List 2 = head → 10 → 50 → 30 → NULL

Output:

head →10 → 10 → 20 → 30 → 50 → 60 → NULL

At this point, we have understood the problem statement. Now we will try to formulate an approach on how to merge 2 unsorted linked lists .

Before moving to the approach section, try to think about how you can approach this problem.

• If stuck, no problem, we will thoroughly see how we can approach this problem in the next section.

Let’s move to the approach section.

### Naive Approach on how to merge two unsorted linked lists.

The naive approach to solve this problem is to first sort the two linked lists and then merge these sorted linked lists into one linked list in increasing order.

Time Complexity of how to merge 2 unsorted linked lists

O(N2 + M2 + (N+M)), where M and N are the lengths of the linked lists. We are first sorting both the lists. Sorting a list takes quadratic time (using bubble sort for sorting). Then we will be merging the two sorted list which will take O(N+M) time. Hence, the total time complexity will be O(N2 + M2 + (N+M)).

Space Complexity of how to merge two unsorted linked lists:

0(1), We are using only a constant amount of extra space.

### Efficient Approach on how to merge two unsorted linked lists

In the efficient approach, we will first concatenate the two given linked lists and then sort the final concatenated linked list by using a sorting algorithm.

Here we will be using bubble sort to sort the linked list. To see how bubble sort works on a linked list, check out this article.

### Algorithm on how to merge 2 unsorted linked lists

The algorithm of this problem is below:

1) First, we will concatenate the two lists.

• In the first list, we will traverse the list until we reach its tail, and after reaching the tail, we will point the next of the tail node to the head node of the second list, storing the concatenated in the first list.

2) Then, we will sort this merged list (we will use bubble sort).

• While sorting, if node→next→data is less than node→data, then we will swap the data.

### Dry Run on how to merge two unsorted linked lists  ### Code Implementation on how to merge 2 unsorted linked lists

```
#include<stdio.h>
#include<stdlib.h>

struct node {
int data;
struct node* next;
};

// Function to print the linked list
{
struct node* tmp;

// list into a temporary node*
// and iterate

while (tmp != NULL) {

printf("%d->",tmp->data);
tmp = tmp->next;
}
}

// Function takes the head of the
// LinkedList and the data as
// argument and if no LinkedList
// exists, it creates one with the
// head pointing to first node.
// If it exists already, it appends
// given node at end of the last node
struct node* getData(struct node* head, int num)
{

// Create a new node
struct node *temp = (struct node *) malloc(sizeof(struct node));

// Insert data into the temporary
// node and point it's next to NULL
temp->data = num;
temp->next = NULL;

// Check if head is null, create a
// and tail of the list
tail = temp;
}

// Else insert the temporary node
// after the tail of the existing
// node and make the temporary node
// as the tail of the linked list
else {

while (tail != NULL) {

if (tail->next == NULL) {
tail->next = temp;
tail = tail->next;
}
tail = tail->next;
}
}

// Return the list
}

// Function to concatenate the two lists
{

// Iterate through the head1 to find the
// last node join the next of last node
while (tail != NULL) {

if (tail->next == NULL
break;
}
tail = tail->next;
}

// return the concatenated lists as a
}

// Sort the linked list using bubble sort
{

// and swaps if the first element
// is greater than the other one.
while (curr->next != NULL) {

temp = curr->next;
while (temp != NULL) {

if (temp->data < curr->data) {
int t = temp->data;
temp->data = curr->data;
curr->data = t;
}
temp = temp->next;
}
curr = curr->next;
}
}

// Driver Code
int main()
{

// Merge the two lists
// in a single list

// Sort the unsorted merged list

// Print the final
// sorted merged list
return 0;
}
```
```public class Prepbytes {

static class node {
int data;
node next;
};

node tmp;

while (tmp.next != null) {
System.out.print(tmp.data + " -> ");
tmp = tmp.next;
}
System.out.println(tmp.data );
}

// Creating a new node
node temp = new node();

temp.data = num;
temp.next = null;

tail = temp;
}

// Else insert the temp node
// after the tail of the existing
// node and make the temp node
// as the tail of the linked list
else {
while (tail != null) {
if (tail.next == null) {
tail.next = temp;
tail = tail.next;
}
tail = tail.next;
}
}

// Return the list
}

// This function will concatenate
static node concatenateList() {

while (tail != null) {
if (tail.next == null && head2 != null) {
break;
}
tail = tail.next;
}

}

// This function will sort the linked list
static void sort() {

// Compares the elements
// If node->next->data is less than node->data
// then we will swap the data.
while (current.next != null) {
temp = current.next;
while (temp != null) {
if (temp.data < current.data) {
int t = temp.data;
temp.data = current.data;
current.data = t;
}
temp = temp.next;
}
current = current.next;
}
}

public static void main(String[] args) {
System.out.println("List1:");
System.out.println("List2:");

sort();
System.out.println("Final merged list:");
}
}
```
```class node:

def __init__(self, x):

self.data = x
self.next = None

while (tmp != None):
print(tmp.data,
end = " -> ")
tmp = tmp.next

temp = node(-1)
temp.data = num
temp.next = None

tail = temp

else:
while (tail != None):
if (tail.next == None):
tail.next = temp
tail = tail.next
tail = tail.next

while (tail != None):
if (tail.next == None
break
tail = tail.next

while (curr.next != None):
temp = curr.next
while (temp != None):
if (temp.data < curr.data):
t = temp.data
temp.data = curr.data
curr.data = t
temp = temp.next
curr = curr.next

if __name__ == '__main__':

```

#### Output

List1:

1 -> 6 -> 10

List2:

5 -> 3 -> 9

Final merged list:

1 -> 3 -> 5 -> 6 -> 9 -> 10

Time Complexity

O((N+M)2), where M and N are the lengths of the linked lists. We are merging given linked lists and iterating the merged list using nested loops to perform bubble sort. The time complexity of bubble sort is O((list.length)2). Hence, the time complexity will be O(((N+M)2).

Space Complexity of how to merge two unsorted linked lists

Note: Also note that to reduce the time complexity, we can use merge sort instead of bubble sort. Merge sort will have a time complexity of O(N * logN), whereas bubble sort has complexity of O(N2).

So, in this blog, we have tried to explain how you can merge two unsorted linked lists to get a sorted linked list. We understood an efficient approach by analyzing algorithm and approach individually on how to merge two unsorted linked listsIf you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

## FAQs on how to merge two unsorted linked lists

1. Why merge sorting is better in linked lists?
2. Generally, in linked lists we can insert elements wherever we can if we have a reference point, even though it requires extra spaces only merge sort can be implemented with or without extra space for linked lists.

3. Which is better Quick sort or Merge sort?
4. Quick sort is better than merge sort because quicksort does not require any extra space for merging whereas merge sort requires as it needs an empty list to merge.

5. Which sorting methods are stable?
6. Sortings such as merge sort, tim sort, counting sort, insertion sort and bubble sort are stable.

7. Which sorting methods are unstable?
8. Sortings such as Quick sort, heap sort and Selection sort are unstable.