ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { int len1 = 0, len2 = 0; auto *p1 = pHead1; auto *p2 = pHead2; while(p1) { len1++; p1 = p1->next; } while(p2){ len2++; p2 = p2->next; } p1 = pHead1; p2 = pHead2; int diff = abs(len1 - len2); if(len1 > len2) while(diff--) p1=p1->next; if(len2 > len1) while(diff--) p2=p2->next; // 这样两个链表的非公共分支长度就一样了 while(p1 && p1->val != p2->val) { p1 = p1->next; p2 = p2->next; } return p1; }
思路:
- 求出两个链表的长度;
- 计算长度差距;
- 步进长的链表,使得链表长度相等;
- 一起前进,直到节点相同;