class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
HashSet nodes = new HashSet<>();
ListNode temp1 = headA;
while (true){
if (temp1 == null){
break;
}
nodes.add(temp1);
temp1 = temp1.next;
}
ListNode temp2 = headB;
while (true){
if (!nodes.add(temp2)){
break;
}
if(temp2 == null){
return null;
}
temp2 = temp2.next;
}
return temp2;
}
}
注意:第14行和第25行 是temp == null还是temp.next == null。 时间复杂度o(m+n),m和n是两个链表的长度。 空间复杂度为o(m)



