時間複雜度爲O(m+n)。
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL){}
};
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2)
{
ListNode* pFirstCommonNode = NULL;
if(pHead1 == NULL || pHead2 == NULL)//若輸入鏈表有一個爲空,返回空結點
return pFirstCommonNode;
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
int pLen1 = 0, pLen2 = 0;
while(pNode1)//分別計算兩個鏈表的長度
{
pNode1 = pNode1 -> next;
pLen1++;
}
while(pNode2)
{
pNode2 = pNode2 -> next;
pLen2++;
}
int offSet = 0;
if(pLen1 < pLen2)//移動鏈表的頭結點,將長鏈表的頭結點與短鏈表的頭結點對齊
{
offSet = pLen2 - pLen1;
while(offSet)
{
pHead2 = pHead2 -> next;
offSet--;
}
}
else if(pLen2 < pLen1)
{
offSet = pLen1 - pLen2;
while(offSet)
{
pHead1 = pHead1 -> next;
offSet--;
}
}
while(pHead1 && pHead2)//如果當前結點不相等,則繼續同步遍歷兩個鏈表直到找到第一個公共結點
{
if(pHead1 == pHead2)
{
pFirstCommonNode = pHead1;
break;
}
else
{
pHead1 = pHead1 -> next;
pHead2 = pHead2 -> next;
}
}
return pFirstCommonNode;//返回第一個公共結點
}