栈真好用但是要占用一点点儿小内存
public ListNode findFristCommonNodeBySet(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while (headA != null) {
set.add(headA);
headA = headA.next;
}
while (headB != null) {
if (set.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
接下里就是我看不懂但是我大受震撼的解法
public ListNode findFristCommonNodeBySet(ListNode headA, ListNode headB) {
if(headA == null || headB == null){
return null;
}
ListNode pa = headA, pb = headB;
while(pa != pb ){
pa = pa.next;
pb = pb.next;
if(pa != pb){
if(pa == null){
pa = headB;
}
if(pb == null){
pb = headA;
}
}
}
return pa;
}