思路:先统计出两个链表的长度M和N,然后让长链表先走M-N步,然后一起走,每步都比较两个链表的节点是否相同,如果相同那么跳出循环,返回第一个公共节点
代码:
struct ListNode{
int val;
ListNode* next;
};
int countLength(ListNode*phead)
{
unsigned int len = 0;
ListNOde*pNode = phead;
while (pNode != NULL)
{
pNode = pNode->next;
len++;
}
return len;
}
ListNode* FindFirstNode(ListNode*phead1, ListNode*phead2)
{
if (phead1 == NULL || phead1 == NULL)
return NULL;
unsigned int M = countLength(phead1);
unsigned int N = countLength(phead2);
int dif;
if (M>N)
{
ListNode*L_long = phead1;
ListNode*L_short = phead2;
dif = M - N;
}
else
{
ListNode*L_long = phead2;
ListNode*L_short = phead1;
dif = N-M;
}
//先在长链表上走几步,再同时在两个链表上遍历
for (int i = 0; i < dif; i++)
L_long = L_long->next;
while (L_long != NULL&&L_short != NULL&&L_long != L_short)
{
L_long = L_long->next;
L_short = L_short->next;
}
ListNode*common = L_short;
return common;
}