Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists.
Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10
Output: 8 -> 15
Since both the linked list has 5, 10 and 20 in common. Therefore these elements are removed and the resultant list is 8 -> 15.
Input: L1 = 0 -> 5 -> 52 -> 21, L2 = 21 -> 5 -> 0 -> 52
Output: [ ]
Since all the elements of the two given linked list are common. So the resultant linked is empty.
- For each element(say X) in the first linked list:
- Traverse the second linked list and check if X is present in the linked list or not.
- If X is not present, then insert X in the resultant linked list as it not common in both linked list.
- For each element(say Y) in the second linked list:
- Traverse the first linked list and check if Y is present in the linked list or not.
- If Y is not present, then insert Y in the resultant linked list as it not common in both linked list.
- The resultant linked list will be the required linked list with no nodes common from the given two linked list.
Below is the implementation of the above approach:
8 -> 5 ->
Time Complexity: O(M * N), where M and N are the lengths of the two given linked list.
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.
- Find the middle of a given linked list in C and Java
- Program for n'th node from the end of a Linked List
- Write a function to get Nth node in a Linked List
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Detect loop in a linked list
- Write a function to delete a Linked List
- Write a function that counts the number of times a given int occurs in a Linked List
- Reverse a linked list
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Write a function to get the intersection point of two Linked Lists
- Function to check if a singly linked list is palindrome
- Clone a linked list with next and random pointer | Set 1
- Memory efficient doubly linked list
- Given a linked list which is sorted, how will you insert in sorted way
- Merge two sorted linked lists
- Print reverse of a Linked List without actually reversing
- Remove duplicates from an unsorted linked list
- Remove duplicates from a sorted linked list
- Reverse a Doubly Linked List
- Split a Circular Linked List into two halves
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.