给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
。
图示两个链表在节点 c1
开始相交:
图
代码:用hashset 存储第一个链表的全部节点,再查找其中包含第二个链表的结点,找到即返回,结束程序。用指针移动链表的节点。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set=new HashSet<>();
ListNode temp=headA;
//
while(temp!=null){
set.add(temp);
temp=temp.next;
}
temp=headB;
while(temp!=null){
if(set.contains(temp)){
return temp;
}
else{
temp=temp.next;
}
}
return null;
}
}