链接
牛客:两个链表的第一个公共结点
LeetCode:剑指 Offer 52. 两个链表的第一个公共节点
思路
两个链表存在公共结点,意味着第一个公共结点之后的都是相同的,就是说,两个链表的尾巴是相同的,我们可以分别算出两个链表的长度之差lenDif ,然后遍历长链表到lenDif的位置,再一起遍历两个链表,找到第一个相同的即可。
代码
牛客:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1 = getLen(pHead1);
int len2 = getLen(pHead2);
int lenDif = 0;
ListNode pLong = null;
ListNode pShort = null;
if(len1 >= len2){
lenDif = len1-len2;
pLong = pHead1;
pShort = pHead2;
} else {
lenDif = len2-len1;
pLong = pHead2;
pShort = pHead1;
}
for(int i = 0; i < lenDif; i++){
pLong = pLong.next;
}
while(pLong != null && pShort != null && pLong != pShort){
pLong = pLong.next;
pShort = pShort.next;
}
ListNode pFirstCommon = pLong;
return pFirstCommon;
}
public int getLen(ListNode pHead){
int len = 0;
ListNode pNode = pHead;
while(pNode!=null){
len++;
pNode = pNode.next;
}
return len;
}
}
LeetCode:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
ListNode pA = headA, pB = headB;
while (pA != pB) {
pA = pA == null ? headB : pA.next;
pB = pB == null ? headA : pB.next;
}
return pA;
}
}