题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { //遍历链表长度 int len1=0; int len2=0; ListNode* l1=pHead1; ListNode* l2=pHead2; while(l1!=nullptr){ len1++; l1=l1->next; } while(l2!=nullptr){ len2++; l2=l2->next; } int d=abs(len1-len2); if(len1>len2){ while(d!=0){ pHead1=pHead1->next; d--; } } else{ while(d!=0){ pHead2=pHead2->next; d--; } } while(pHead1!=pHead2){ pHead1=pHead1->next; pHead2=pHead2->next; } return pHead1; } };