1 class Solution { 2 public: 3 ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { 4 if (pHead1 == nullptr || pHead2 == nullptr)return nullptr; 5 int L1 = 1, L2 = 1; 6 ListNode *p1 = pHead1, *p2 = pHead2; 7 while (p1->next != nullptr) 8 { 9 p1 = p1->next; 10 ++L1; 11 } 12 while (p2->next != nullptr) 13 { 14 p2 = p2->next; 15 ++L2; 16 } 17 if (p1 != p2)return nullptr;//最后一个节点不相同,则没有相交点 18 p1 = pHead1; 19 p2 = pHead2; 20 if (L1 >= L2) 21 for (int i = 0; i < L1 - L2; ++i)p1 = p1->next; 22 else 23 for (int i = 0; i < L2 - L1; ++i)p2 = p2->next; 24 while (p1 != p2) 25 { 26 p1 = p1->next; 27 p2 = p2->next; 28 } 29 return p1; 30 } 31 };
原文:https://www.cnblogs.com/zzw1024/p/11706123.html