-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersection_Of_two_LL.cpp
More file actions
42 lines (42 loc) · 961 Bytes
/
Intersection_Of_two_LL.cpp
File metadata and controls
42 lines (42 loc) · 961 Bytes
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int len (ListNode* a) {
if (!a) return 0;
int cnt=0;
while (a){
cnt++;
a = a->next;
}
return cnt;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA && !headB)
return NULL;
auto curr1 = headA;
auto curr2 = headB;
int diff = len(headA) - len(headB);
while (diff > 0) {
curr1 = curr1->next;
diff--;
}
while (diff < 0) {
curr2 = curr2->next;
diff++;
}
while (curr1 && curr2) {
if(curr1 == curr2)
return curr1;
curr1 = curr1->next;
curr2 = curr2->next;
}
return NULL;
}
};