-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion52.cpp
More file actions
45 lines (42 loc) · 933 Bytes
/
Copy pathquestion52.cpp
File metadata and controls
45 lines (42 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
输入两个链表,找出它们的第一个公共结点。
Xiaobin Tian;
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
int lengthoflist(ListNode *Head){
int length = 0;
auto p = Head;
while(p != nullptr){
p = p->next;
++length;
}
return length;
}
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == nullptr || pHead2 == nullptr)
return nullptr;
int length1 = lengthoflist(pHead1);
int length2 = lengthoflist(pHead2);
ListNode * p = pHead1, *q = pHead2;
int lengthdif = length1 - length2;
if(length1 < length2){
q = pHead1;
p = pHead2;
lengthdif = length2 - length1;
}
for(int i = 0; i < lengthdif; ++i)
p = p->next;
while(p != nullptr && q != nullptr && p->val != q->val){
p = p->next;
q = q->next;
}
return p;
}
};