I am doing LC:60 which is about finding intersection of two linked lists. I wrote following code based on this logic
- find length of both lists.
- advance 1 pointer of long list to the difference of the length
- compare both lists from this point onwards.
This is working for all test-cases except for test case where two lists have same input i.e., [2, 2, 4, 5, 4] but the intersection node is node 4.
Here is the code
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int aN = 0;
ListNode a = headA;
while (a != null) {
aN++;
a = a.next;
}
int bN = 0;
ListNode b = headB;
while (b != null) {
bN++;
b = b.next;
}
ListNode longList = (aN > bN) ? headA : headB;
ListNode shortList = (aN < bN) ? headA : headB;
for (int i = 0; i < Math.abs(aN - bN); i++) {
longList = longList.next;
}
while (longList != null && shortList != null) {
if (longList == shortList) { return longList; }
longList = longList.next;
shortList = shortList.next;
}
return null;
}
}
The problem is in these statements:
If both lists have the same size, then both
longListandshortListwill be set toheadB. You should have a ternary condition that is the exact opposite (<=for the second one), or maybe more intuitive, use the same condition but swap the operands in the second assignment: