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).
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Merge Sort for Linked Lists
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- Merge two sorted linked lists
- Merge K sorted linked lists | Set 1
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- In-place Merge two linked lists without changing links of first list
- Merge two sorted linked lists such that merged list is in reverse order
- Merge Sort for Doubly Linked List
- Iterative Merge Sort for Linked List
- Sorted merge of two sorted doubly circular linked lists
- Merge two sorted lists (in-place)
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Merge a linked list into another linked list at alternate positions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.