Write a function named intersection
that accepts as parameters two pointers to nodes representing the fronts of two linked lists that may contain duplicate regions, and returns a pointer to the front of that intersection, or nullptr
if the lists do not intersect.
For example, suppose your function is given the following lists:
list1 -> 1 -> 5 -> 4 -> 8 -> 3 -> 15 /
list2 -> 2 -> 6 -> 8 -> 3 -> 15 /
A call to your function should return a pointer to the node containing 8
from the first list, since that is the beginning of the intersecting region.
For this problem you should assume that if you ever see a value in common between the two lists, that the rest of the lists will be duplicates in part of an intersection.
So, in other words, if you see that the lists both contain an 8
in the example above, you may assume that the remaining elements of both lists are the same.
Constraints:
Do not modify the lists that are passed in.
Do not create new ListNode
objects, though you may create pointers to nodes.
Assume that you are using the ListNode
structure as defined below:
struct ListNode {
int data; // value stored in each node
ListNode* next; // pointer to next node in list (nullptr if none)
};