題目描述
輸入兩個(gè)鏈表,找出它們的第一個(gè)公共結(jié)點(diǎn)烁焙。
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL||pHead2==NULL)
return NULL;
int m = getLength(pHead1),n = getLength(pHead2);
ListNode *p1 = pHead1;
ListNode *p2 = pHead2;
if(m>n)
{
int k = m - n;
while(k>0)
{
p1 = p1->next;
k--;
}
while(p1!=p2&&p1&&p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
else
{
int k = n - m;
while(k>0)
{
p2 = p2->next;
k--;
}
while(p1!=p2&&p1&&p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
}
int getLength(ListNode* list)
{
int count = 0;
while(list!=NULL)
{
list = list->next;
count ++;
}
return count;
}
};