题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
int ListLen(ListNode* p) {
int n=0;
while(p) {
p=p->next;
n++;
}
return n;
}
ListNode* FindFirstCommonNode( ListNode* head1, ListNode* head2) {
ListNode* p1=head1;
ListNode* p2=head2;
int len1=ListLen(p1);
int len2=ListLen(p2);
int gap=0;
if(len1>len2) {
gap = len1-len2;
while(gap--) {
p1=p1->next;
}
}else{
gap = len2-len1;
while(gap--) {
p2=p2->next;
}
}
while(p1 && p2) {
if(p1->val == p2->val) return p1;
p1=p1->next;
p2=p2->next;
}
return nullptr;
}
};