题目:两个单向链表,找出它们的第一个公共结点。
链表的结点定义为:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
思路:如果有公共结点,那么从公共结点之后都是一样的,假设一个长m,一个长n,那么这两个之间的差值之前的结点不可能是公共的,所以长的一个先走差值,然后两个一起走 判断
int GetListLength(ListNode* head)
{
int len =0;
ListNode* pnode = head;
while (pnode!=NULL)
{
len++;
pnode = pnode->m_pnext;
}
return len;
}
ListNode* FindTheFirstCommon(ListNode* phead1,ListNode* phead2)
{
int len1 = GetListLength(phead1);
int len2 = GetListLength(phead2);
int lendiff = len1 - len2;
ListNode* plonglist = phead1;
ListNode* pshortlist = phead2;
if(len2 > len1)
{
plonglist = phead2;
pshortlist = phead1;
lendiff = len2 - len1;
}
for (int i=0;i<lendiff;++i)
plonglist = plonglist->m_pnext;
while (plonglist!=NULL && pshortlist!=NULL && plonglist != pshortlist)
{
plonglist = plonglist->m_pnext;
pshortlist = pshortlist->m_pnext;
}
ListNode* common = plonglist;
return common;
}