题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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 *p1,*p2,*longL,*shortL;
p1 = pHead1;
p2 = pHead2;
if(pHead1 == NULL || pHead2 == NULL){
return NULL;
};
int len1 = 0,len2 = 0,dist = 0;
while(p1){
p1 = p1 ->next;
len1++;
}
while(p2){
p2 = p2 -> next;
len2++;
}
p1 = pHead1;
p2 = pHead2;
if(len1 >= len2){
longL = p1;
shortL = p2;
dist = len1 - len2;
}else{
shortL = p1;
longL = p2;
dist = len2 - len1;
}
while(dist--){
longL = longL -> next;
}
while(longL){
if(longL == shortL){
return longL;
}
else{
longL = longL -> next;
shortL = shortL -> next;
}
}
return NULL;
}
定会同时遍历完,这样当两个链表指向同一个节点的时候,这个节点就是公共节点
莉莉丝游戏公司福利 614人发布
查看30道真题和解析