题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* first = pHead2; //保存链表2的头结点地址
while(pHead1)
{
while(pHead2)
{
if(pHead2->val == pHead1->val)
{
if((pHead1->next == NULL&&pHead2->next == NULL)||(pHead1->next!=NULL&&pHead2->next!=NULL&&pHead1->next->val == pHead2->next->val)) //找到第一个公共结点
{
return pHead1;
}
}
pHead2 = pHead2->next;
}
pHead1 = pHead1->next;
pHead2 = first;
}
return NULL;
}

查看8道真题和解析