I tried to solve following Leetcode problem where you have to find the intersection-node of two linked lists, and return it (or null, if there is none).
I know there are simpler solutions than the one I came up with, but I’d like to know whats wrong with my approach:
Let x be the number of nodes between the start of list A and the intersection; same for y and list B. And let z be the distance between the intersection and the end of the lists (see picture).
Let’s assume that list A is longer than B, therefore y<x.
If I let two pointers start from the heads of both lists, the pointer of B is going to reach the end while pointer A is still in the list. Both pointers traveled the same distance y+z. Since list A is longer than B by (x+z)-(y+z) = (x-y), pointer A is at the node (y+z)-(x-y) = z-y. Now I save this pointer in the variable “middle” and I let another pointer “newStart” start at the beginning of B. If I let both of them traverse the list, “middle” is going to reach the end after y nodes so pointer “newStart” will be at position y (the intersection).
public static ListNode getIntersectionNode(ListNode headA, ListNode headB){
// First iteration
ListNode firstA = headA;
ListNode firstB = headB;
ListNode middle;
ListNode newStart;
while (true){
if (firstA.next==null){
middle = firstB;
newStart = headA;
break;
}
if (firstB.next==null){
middle = firstA;
newStart = headB;
break;
}
firstA = firstA.next;
firstB = firstB.next;
}
// second iteration
while (middle != null){
middle = middle.next;
newStart= newStart.next;
}
return newStart;
}
However this doesn’t work, and I’m having a hard time debugging and understanding whats wrong in my code.