C Program For Union And Intersection Of Two Linked Lists
Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.
Input: List1: 10->15->4->20 List2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10
Method 1 (Simple):
The following are simple algorithms to get union and intersection lists respectively.
1. Intersection (list1, list2):
Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.
2. Union (list1, list2):
Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method.
First list is 10 15 4 20 Second list is 8 4 2 10 Intersection list is 4 10 Union list is 2 8 20 4 15 10
- Time Complexity: O(m*n).
Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively.
For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.
For intersection: For every element in list-1 we check if that element is also present in list-2.
- Auxiliary Space: O(1).
No use of any data structure for storing values.
Method 2 (Use Merge Sort):
In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection.
The following are the steps to be followed to get union and intersection lists.
- Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
- Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
- Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.
The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.
Please refer complete article on Union and Intersection of two Linked Lists for more details!