-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
160. Intersection of Two Linked List
48 lines (45 loc) · 1.14 KB
/
160. Intersection of Two Linked List
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
//T.C - O(n)
//S.C - O(n)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*a = headA;
ListNode*b = headB;
while(a->next && b->next){
if(a==b){
return a;
}
a = a->next;
b = b->next;
}
//intersection hai hi nhi
if(a->next ==0 && b->next ==0 && a!=b)return 0;
if(a->next==0){
//b is bigger
//we nee to found how much bigger it is
int blen=0;
while(b->next){
blen++;
b = b->next;
}
while(blen--){
headB = headB->next;
}
}
else{
int alen =0;
while(a->next){
alen++;
a = a->next;
}
while(alen--){
headA = headA->next;
}
}
while(headA != headB){
headA = headA->next;
headB = headB->next;
}
return headA;
}
};