描述
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
分析
计算出两条链表的长度,算出长度差值,让链表长的先走n使得两个链表同长,然后同步遍历若有相交返回交点,没有返回空。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode ha = headA;
ListNode hb = headB;
int n1 = 0, n2 = 0;
while(ha != null){
ha = ha.next;
n1++;
}
while(hb != null){
hb = hb.next;
n2++;
}
ha = headA;
hb = headB;
if(n1 > n2){
for(int i = 0; i < n1 - n2; i++){
ha = ha.next;
}
}else{
for(int i = 0; i < n2 - n1; i++){
hb = hb.next;
}
}
while(ha != hb){
ha = ha.next;
hb = hb.next;
}
return ha;
}
}