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).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- Merge Sort for Linked Lists
- Merge two sorted linked lists such that merged list is in reverse order
- In-place Merge two linked lists without changing links of first list
- Sorted merge of two sorted doubly circular linked lists
- Merge odd and even positioned nodes of two Linked Lists alternately
- Merge two sorted linked lists
- Merge two unsorted linked lists to get a sorted list
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge K sorted linked lists | Set 1
- 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 two sorted lists (in-place)
- Merge Sort for Doubly Linked List
- Iterative Merge Sort for Linked List
- Merge a linked list into another linked list at alternate positions
- Merge two sorted linked list without duplicates
- Compare two strings represented as linked lists
- Subtract Two Numbers represented as Linked Lists
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.