-
Notifications
You must be signed in to change notification settings - Fork 1
/
052-两个链表的第一个公共结点.cpp
45 lines (43 loc) · 1.22 KB
/
052-两个链表的第一个公共结点.cpp
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
/*
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;
int listLength1=GetListLength(pHead1);
int listLength2=GetListLength(pHead2);
ListNode* longListNode=pHead1;
ListNode* shortListNode=pHead2;
int difLength=listLength1-listLength2;
if(listLength1<listLength2){
shortListNode=pHead1;
longListNode=pHead2;
difLength=listLength2-listLength1;
}
for(int i=0;i<difLength;i++){
longListNode=longListNode->next;
}
while(longListNode!=nullptr&&shortListNode!=nullptr&&longListNode->val!=shortListNode->val){
longListNode=longListNode->next;
shortListNode=shortListNode->next;
}
return longListNode;
}
int GetListLength(ListNode* pHead){
if(pHead==nullptr)
return 0;
int length=1;
while(pHead->next!=nullptr){
pHead=pHead->next;
length++;
}
return length;
}
};