logo CodeStepByStep logo

intersection

Language/Type: C++ linked lists pointers
Author: Julie Zelenski (on 2020/08/31)

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)
};
Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.