题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
//快慢指针,问题出在最后的return上 如果上述条件都不符合的话,返回空,这道题还可以用哈希表来做 unorderedmap
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
ListNode* pTail1=pHead1;
ListNode* pTail2=pHead2;
ListNode* nFast, *nSlow;
int len1=0, len2=0;
while (pTail1)
{
pTail1 = pTail1->next;
len1++;
}
while (pTail2)
{
pTail2 = pTail2->next;
len2++;
}
if (len1 >= len2)
{
int i = len1 - len2;
nFast = pHead1;
nSlow = pHead2;
while (i)
{
nFast = nFast->next;
i--;
}
}
else
{
int i = len2 - len1;
nFast = pHead2;
nSlow = pHead1;
while (i)
{
nFast = nFast->next;
i--;
}
}
while (nFast)
{
if (nFast == nSlow)
return nFast;
nFast = nFast->next;
nSlow = nSlow->next;
}
return NULL;
}
};
查看14道真题和解析