题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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
int i=0,j=0;
struct ListNode* p1=pHead1;
struct ListNode* p2=pHead2;
while(p1){//链表长度
i++;
p1=p1->next;
}
while(p2){//链表长度
j++;
p2=p2->next;
}
//两个单向链表的长度差,即为先走的步数
if(i>j){//pHead1表长
while(i-j){
pHead1=pHead1->next;
i--;
}
}else{//pHead2表长
while(i-j){
pHead2=pHead2->next;
j--;
}
}
while(pHead1!=pHead2){//地址相同时,即为第一个公工节点
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return pHead1;//返回公共节点
}
