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).
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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)
- Merge two unsorted linked lists to get a sorted list
- 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
- Merge two sorted linked list without duplicates
- Identical Linked Lists
- First common element in two linked lists
- Add Two Numbers Represented by Linked Lists | Set 3
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.