Intersection Point of Two Lists
Given the head of two linked lists, find out if they intersect and return the point of intersection.
Statement
Given the head nodes of two linked lists, return the node at which the two lists intersect. We will return null if we do not find any intersection between the two linked lists.
Note: The input linked list will not have cycles in it.
Example
In the below example, lists do not intersect each other.
After adding nodes 12 and 27 in the linked list head2
, the list now has the same nodes as the linked list head1
.
However, in the below example, both lists intersect at the node with data 12. The node 4 in linked list head2
points to node 12 and the node 11 in linked list head1
points to node 12 (with the same address).
Sample input
[13, 4, 12, 27]
[29, 23, 82, 11, 12, 27]
Expected output
12
Try it yourself
The linked lists have to physically intersect. This means that their addresses need to be the same. If two nodes have the same data but their addresses are not the same, the lists won’t intersect and the function should return null.
#include "LinkedList.cpp"using namespace std;LinkedListNode* Intersect(LinkedListNode* head1, LinkedListNode* head2) {//TODO: Write - Your - Codereturn head1;}
Solution 1
Firstly, we’ll find the lengths of both and ...