Difference of two Linked Lists using Merge sort
Given two Linked List, the task is to create a Linked List to store the difference of Linked List 1 with Linked List 2, i.e. the elements present in List 1 but not in List 2.
List1: 10 -> 15 -> 4 ->20,
List2: 8 -> 4 -> 2 -> 10
Output: 15 -> 20
In the given linked list elements 15 and 20 are present in the list 1 but not in list 2.
List1: 2 -> 4 -> 8 -> 10,
List2: 8 -> 10
Output: 2 -> 4
In the given linked list 1 elements 2 and 4 are present in the list 1 but not in list 2.
- Sort both Linked Lists using merge sort.
- Linearly scan both sorted lists to get the difference with two pointers on it p1 and p2 and compare the data of the nodes in the linked list and perform following in below three cases –
- If p1.data == p2.data then, p1.data cannot be in the difference list, So move the pointers p1 and p2 ahead.
- If p1.data > p2.data then, p1.data may be present in list 2 in further nodes, So move the pointer p2 ahead.
- If p1.data > p2.data then, p1.data cannot be present in list 2 now, So add the data of p1 into difference list and move pointer p1 ahead.
- If the end of list 2 is reached, insert all the remaining elements of list 1 into the difference list.
Below is the implementation of the above approach.
2 6 8
Time complexity: O(M Log M + N Log N).