两个链表的第一个公共结点
作者:
安然_fc00 | 来源:发表于
2017-03-24 22:17 被阅读0次 ListNode* FindFirstCommonNode( ListNode* head1, ListNode* head2) {
int Length1 = GetLength(head1);
int Length2 = GetLength(head2);
int LengthDif = Length1 - Length2;
ListNode* pLongListHead = head1;
ListNode* pShortListHead = head2;
if (Length1 < Length2)
{
LengthDif = Length2 -Length1;
pLongListHead = head2;
pShortListHead = head1;
}
for(int i = 0; i<LengthDif ;i++)
{
pLongListHead = pLongListHead->next;
}
while(pLongListHead != NULL && pShortListHead != NULL && pLongListHead != pShortListHead)
{
pLongListHead = pLongListHead->next;
pShortListHead = pShortListHead->next;
}
return pLongListHead;
}
int GetLength(ListNode* head){//获取链表的长度
int length = 0;
while(head != NULL)
{
length++;
head = head->next;
}
return length;
}
本文标题:两个链表的第一个公共结点
本文链接:https://www.haomeiwen.com/subject/wxdtottx.html
网友评论