两个链表的第一个公共结点

Desicription

输入两个链表,找出它们的第一个公共结点。

Solution

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
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
auto pointTemp = pHead1;
int length1 = 0;
int length2 = 0;
while(pointTemp) {
pointTemp = pointTemp->next;
length1++;
}
pointTemp = pHead2;
while(pointTemp) {
pointTemp = pointTemp->next;
length2++;
}
while(true) {
if(length1 > length2) {
pHead1 = pHead1->next;
length1--;
} else if(length1 < length2) {
pHead2 = pHead2->next;
length2--;
} else {
if(pHead1 == pHead2) {
return pHead1;
} else {
pHead1 = pHead1->next;
pHead2 = pHead2->next;
length1--;
length2--;
}
}
}
}
};