我们可以有如下步骤
- 先得到两个链表的长度
- 知道较长的链表比 较短的链表多几个节点
- 先在较长的链表上走若干步
- 两个链表上同时遍历,找到的第一个相同的结点就是他们的第一个公共结点。
例如:得到两个链表的长度分别为5和6,先让长链表走1步,到结点4。接下来同时让两个链表分别从结点1和结点4走,直至找到结点6。
struct ListNode {
int val;
struct ListNode *next;
};
//输入两个链表,找出他们的第一个公共结点
int GetListLenth(ListNode *pHead)
{
int len = 0;
ListNode *pNode = pHead;
while (pNode != NULL)
{
++len;
pNode = pNode->next;
}
return len;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
//得到两个链表的长度
int len1 = GetListLenth(pHead1);
int len2 = GetListLenth(pHead2);
int lenth= len1 - len2;
ListNode *pListLong = pHead1;
ListNode *pListShort = pHead2;
if (len2 > len1)
{
pListLong = pHead2;
pListShort = pHead1;
lenth = len2 - len1;
}
//先在长链表上走几步,再同时遍历
for (int i = 0; i < lenth; ++i)
{
pListLong = pListLong->next;
}
while ((pListLong != NULL) && (pListShort != NULL) && (pListLong != pListShort))
{
pListLong = pListLong->next;
pListShort = pListShort->next;
}
ListNode *pFirstCommon = pListLong;
return pFirstCommon;
}