Intersection of two sorted Linked lists
Given two lists sorted in increasing order, create a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
Given two lists sorted in increasing order, create a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.
For example, let the first linked list be 1->2->3->4->6 and second linked list be 2->4->6->8, then your function should create a third list as 2->4->6.
Basic Logic:
- If any of list is empty then return non-empty list
- Iterate till both lists nodes are not empty.
- If
node1.data > node2.data
then move of step a head in list2 - If
node1.data < node2.data
then move of step a head in list1 - If
node1.data == node2.data
, then add data to result list and increase both list pointers
Note:
Below implementation is little optimized.
Latest Source Code:
Github: SortedListIntersection.java
Output:
1 3 8 20 36 2 3 7 8 12 16 20 23 3 8 20