-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question35.cpp
53 lines (48 loc) · 1.16 KB
/
Question35.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
35 -> Intersection of two list
Solution :
class Solution {
public:
int getlen(ListNode*node){
int len=0;
while(node){
node=node->next;
len++;}
return len;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// unordered_set<ListNode*>s;
// while(headA){
// s.insert(headA);
// headA=headA->next;
// }
// while(headB){
// if(s.find(headB)!=s.end())
// return headB;
// headB=headB->next;
// }
// return NULL;
int len1=getlen(headA);
int len2=getlen(headB);
ListNode*curr1=headA;
ListNode*curr2=headB;
int lendiff=abs(len1-len2);
if(len1>len2){
while(lendiff--){
curr1=curr1->next;
}
}
else{
while(lendiff--){
curr2=curr2->next;
}
}
while(curr1&&curr2){
if(curr1==curr2){
return curr1;
}
curr1=curr1->next;
curr2=curr2->next;
}
return NULL;
}
};