题解 | 两个链表的第一个公共结点 一种不计算长度的算法
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//计算长度 然后快慢相遇?
//可以 但效率不高 可以尝试不计算长度
if(pHead1==nullptr||pHead2==nullptr)return nullptr;
ListNode* cur1=pHead1,*cur2=pHead2;
while(cur1!=cur2){
if(cur1!=nullptr)cur1=cur1->next;
else cur1=pHead2;
if(cur2!=nullptr)cur2=cur2->next;
else cur2=pHead1;
}
return cur1;
}
};
查看25道真题和解析
