-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode160.cpp
56 lines (55 loc) · 1.21 KB
/
leetcode160.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
int lengthoflist(ListNode *head)
{
if(head == NULL)
return 0;
int result = 0;
ListNode* node;
node = head;
while(node != NULL)
{
result++;
node = node->next;
}
return result;
}
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int aLen,bLen;
if(headA == NULL || headB == NULL)
return NULL;
else{
aLen = lengthoflist(headA);
bLen = lengthoflist(headB);
int dist;
if(aLen < bLen){
dist = bLen - aLen;
while(dist){
headB = headB->next;
dist--;
}
}
if(aLen > bLen){
dist = aLen - bLen;
while(dist){
headA = headA->next;
dist--;
}
}
while(headB != headA){
headB = headB->next;
headA = headA->next;
}
return headB;
}
}
};