题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
#include <math.h>
#include <stdio.h>
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 )
{
if(pHead1==NULL&&pHead2!=NULL)return NULL;
if(pHead1!=NULL&&pHead2==NULL)return NULL;
if(pHead1==NULL&&pHead2==NULL)return NULL;
struct ListNode* p=pHead1;
int count1=1,count2=1;
while(p->next!=NULL)
{
count1++;
p=p->next;
}
p=pHead2;
while(p->next!=NULL)
{
count2++;
p=p->next;
}
struct ListNode* slow=count1>count2?pHead2:pHead1;//slow=p2
struct ListNode* fast=count1>count2?pHead1:pHead2;//fast=p1
for(int i=0;i<(abs(count1-count2));i++)
{
fast=fast->next;
}
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
