题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null) return null;
int diff = diff(pHead1, pHead2);
if(diff > 0) {
while(diff > 0) {
pHead1 = pHead1.next;
diff--;
}
} else {
while(diff < 0) {
pHead2 = pHead2.next;
diff++;
}
}
while(pHead1 != null && pHead2 != null) {
if(pHead1 == pHead2) return pHead1;
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
private int diff(ListNode l1, ListNode l2) {
int length1 = 0;
int length2 = 0;
while(l1.next != null) {
length1++;
l1 = l1.next;
}
while(l2.next != null) {
length2++;
l2 = l2.next;
}
return length1 - length2;
}
}
查看1道真题和解析