/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if(pHead1==nullptr||pHead2==nullptr) return nullptr; ListNode * pHeadnew1=pHead1; ListNode * pHeadnew2=pHead2; unsigned int length1=getlistlength(pHeadnew1); unsigned int length2=getlistlength(pHeadnew2); unsigned int distance; if(length1>length2) { distance =length1-length2; while(distance) { pHeadnew1=pHeadnew1->next; --distance; } } else { distance =length2-length1; while(distance) { pHeadnew2=pHeadnew2->next; --distance; } } //链表在此处已经对齐了 while(pHeadnew1!=pHeadnew2&&(pHeadnew1!=nullptr)&&(pHeadnew2!=nullptr))//是相同节点 { pHeadnew1=pHeadnew1->next; pHeadnew2=pHeadnew2->next; } ListNode * pfirstcommon = pHeadnew1; return pfirstcommon; } public: unsigned int getlistlength(ListNode* phead) { if (phead==nullptr) return 0; unsigned int length=0; while(phead) { phead = phead->next; length++; } return length; } };
原文:https://www.cnblogs.com/cgy1012/p/11426971.html