题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
#include <math.h>
struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* p1=pHead1;
struct ListNode* p2=pHead2;
if(p1==NULL||p2==NULL)return NULL;
while(p1!=p2){
p1=p1->next;
p2=p2->next;
//p1,p2两指针同时指空时说明两链表无公共部分
if(p1==NULL&&p2!=NULL){p1=pHead2;}
if(p2==NULL&&p1!=NULL){p2=pHead1;}
}
return p1;
}

查看14道真题和解析