2つの方法があります。1つは2つの補助スタックを使用する方法で、もう1つは長さを取得する方法です。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int length_a = 0;
int length_b = 0;
ListNode temp_a = headA;
ListNode temp_b = headB;
while(temp_a!=null){
length_a++;
temp_a = temp_a.next;
}
while(temp_b!=null){
length_b++;
temp_b = temp_b.next;
}
temp_a = headA;
temp_b = headB;
if(length_a > length_b){
for(int count = 0;count<length_a - length_b;count++){
temp_a = temp_a.next;
}
for(int count = 0;count<length_b;count++){
if(temp_a == temp_b){
return temp_a;
}
temp_a = temp_a.next;
temp_b = temp_b.next;
}
}else{
for(int count = 0;count<length_b - length_a;count++){
temp_b = temp_b.next;
}
for(int count = 0;count<length_a;count++){
if(temp_a == temp_b){
return temp_a;
}
temp_a = temp_a.next;
temp_b = temp_b.next;
}
}
return null;
}