题目描述
输入两个链表,找出它们的第一个公共结点。
/* 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; int lengthlong = CountLen(pHead1); int lengthshort = CountLen(pHead2); int gap = lengthlong - lengthshort; ListNode* pLong = pHead1; ListNode* pShort = pHead2; if(gap<0){ pLong = pHead2; pShort = pHead1; gap = -gap; } for(int i=0;i<gap;i++) pLong = pLong->next; while(pLong && pShort &&pLong!=pShort){ pLong = pLong->next; pShort = pShort->next; } return pLong; } int CountLen(ListNode* pHead) { int count = 0; while(pHead) { count++; pHead = pHead->next; } return count; } };