Question: Given head nodes of two linked lists that may or may not intersect, find out if they intersect and return the point of intersection; return null otherwise.
Solution time:o(m+n),space o(1):

Here's the code:
public static LinkedListNode intersect(
LinkedListNode head1,
LinkedListNode head2) {
LinkedListNode list1node = null;
int list1length = get_length(head1);
LinkedListNode list2node = null;
int list2length = get_length(head2);
int length_difference = 0;
if(list1length >= list2length) {
length_difference = list1length - list2length;
list1node = head1;
list2node = head2;
} else {
length_difference = list2length - list1length;
list1node = head2;
list2node = head1;
}
while(length_difference > 0) {
list1node = list1node.next;
length_difference--;
}
while(list1node != null) {
if(list1node == list2node) {
return list1node;
}
list1node = list1node.next;
list2node = list2node.next;
}
return null;
}
However, I'm thinking is there a possible that the Intersection Point just appear at the position before d steps in the longer list? Like:

I'm confused, please help me clear my mind, thank you!
A node can only has one successor. While in the second picture, the intersection node get two successors, which is impossible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With