要求两个链表第一个公共节点,一种直观的思想就是用一个链表的每一个节点与另一个链表的所有节点进行比较,看有没有相同的。这种方法时间复杂度为O(m*n)。
我们不妨换种思路,如果两个链表有相交的节点,那么之后所有的节点都相同。所以,先让长链表走完多的步长,然后看此时节点是否相同即可。
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
{
int len1=len(pHead1 );
int len2=len(pHead2 );
int dis;
if(len1>len2)
{
dis=len1-len2;
for(int i=0;i<dis;i++)
pHead1 =pHead1 ->next ;
}else
{
dis=len2-len1;
for(int i=0;i<dis;i++)
pHead2 =pHead2->next ;
}
while(pHead1!=NULL &&pHead2!=NULL )
{
if(pHead1 ==pHead2 )
return pHead1 ;
pHead1 =pHead1 ->next ;
pHead2 =pHead2 ->next ;
}
return NULL ;
}
int len(ListNode *p)
{
int cnt=0;
while(p!=NULL )
{
cnt++;
p=p->next ;
}
return cnt;
}