-
Notifications
You must be signed in to change notification settings - Fork 12
/
getIntersectionNode.cpp
43 lines (43 loc) · 1.14 KB
/
getIntersectionNode.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int getLength(ListNode *head) {
int ret = 0;
while (head) {
ret++;
head = head->next;
}
return ret;
}
ListNode* Solution::getIntersectionNode(ListNode* A, ListNode* B) {
if(!A || !B)
return NULL;
int lenA = getLength(A), lenB = getLength(B);
int lenDiff = lenA - lenB;
ListNode *pa = A;
ListNode *pb = B;
if(lenDiff > 0) {
while(lenDiff != 0) {
pa = pa->next;
lenDiff--;
}
}
else if(lenDiff < 0) {
while(lenDiff != 0) {
pb = pb->next;
lenDiff++;
}
}
while(pa && pb) {
if(pa == pb)
return pa;
pa = pa->next;
pb = pb->next;
}
return NULL;
}