题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
灵活运用链表长度加减法,对链表分段相加长度相同
a+b+c = c+b+a
双指针指向相同即使共同部分b的入口节点,a+b到尾部则跳转另一链表c+b,同理,c+b到尾部则跳转a+b。
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode* first = pHead1;
ListNode* second = pHead2;
while(first != second){
first = (first==nullptr?pHead2:first->next);
second = (second==nullptr?pHead1:second->next);
}
return first;
}
};