Input: List 1 = 3 -> 1 -> 5, List 2 = 6-> 2 -> 4
Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6
Input: List 1 = 4 -> 7 -> 5, List 2 = 2-> 1 -> 8 -> 1
Output: 1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8
Naive Approach: The naive approach is to sort the given linked lists and then merge the two sorted linked lists together into one list in increasing order.
To solve the problem mentioned above the naive method is to sort the two linked lists individually and merge the two linked lists together into one list which is in increasing order.
Efficient Approach: To optimize the above method we will concatenate the two linked lists and then sort it using any sorting algorithm. Below are the steps:
- Concatenate the two lists by traversing the first list until we reach its a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list.
- Sort the above-merged linked list. Here, we will use bubble sort. So, if node->next->data is less then node->data, then swap the data of the two adjacent nodes.
Below is the implementation of the above approach:
1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8
Time Complexity: O(M*N) where M and N are the length of the two given linked lists.
- Merge two sorted linked lists such that merged list is in reverse order
- Sorted merge of two sorted doubly circular linked lists
- Merge K sorted linked lists | Set 1
- Merge two sorted linked lists
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge K sorted Doubly Linked List in Sorted Order
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Merge two sorted linked list without duplicates
- In-place Merge two linked lists without changing links of first list
- Merge two sorted lists (in-place)
- Merge Sort for Linked Lists
- Difference of two Linked Lists using Merge sort
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- Merge a linked list into another linked list at alternate positions
- Intersection of two Sorted Linked Lists
- Create a linked list from two linked lists by choosing max element at each position
- Remove duplicates from an unsorted linked list
- Insert value in sorted way in a sorted doubly linked list
- Remove duplicates from an unsorted doubly linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.