题目描述
思路分析
链表模拟。
先求出俩链表的节点数
c
n
t
1
cnt1
cnt1和
c
n
t
2
cnt2
cnt2,然后先走到往后节点数一样的地方,然后
c
n
t
1
,
c
n
t
2
cnt1,cnt2
cnt1,cnt2一起往后移动,判断地址是否相等
代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* head1, ListNode* head2) {
int cnt1=0,cnt2=0;
auto a=head1;
while(a) cnt1++,a=a->next;
a=head2;
while(a) cnt2++,a=a->next;
a=head1;
auto b=head2;
while(cnt1>cnt2) a=a->next,cnt1--;
while(cnt2>cnt1) b=b->next,cnt2--;
if(a==b) return a;
while(a&&b&&a->next!=b->next) a=a->next,b=b->next;
return a->next;
}
};