forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
57 lines (52 loc) · 1.11 KB
/
solution.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
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
if(headA == NULL || headB == NULL)
return NULL;
int countA = 0;
ListNode *TA = headA;
while(TA->next != NULL)
{
TA = TA->next;
countA++;
}
int countB = 0;
ListNode *TB = headB;
while(TB->next != NULL)
{
TB = TB->next;
countB++;
}
if(TA != TB)
return NULL;
int temp;
if(countA > countB)
{
temp = countA - countB;
while(temp--)
headA = headA->next;
}
else
{
temp = countB - countA;
while(temp--)
headB = headB->next;
}
while(headA != headB)
{
headA = headA->next;
headB = headB->next;
}
return headA;
}
};