-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathgetIntersectionNode.cpp
More file actions
44 lines (43 loc) · 1.11 KB
/
Copy pathgetIntersectionNode.cpp
File metadata and controls
44 lines (43 loc) · 1.11 KB
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
/**
* 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) {
int n=0;
int m=0;
ListNode* temp=headA;
while(temp!=NULL){
temp=temp->next;
n++;
}
temp=headB;
while(temp!=NULL){
temp=temp->next;
m++;
}
// taking as headA is longer
int d=abs(n-m);
if(m>n){
temp=headA;
headA=headB;
headB=temp;
}
while(d--){
headA=headA->next;
}
while(headA!=NULL && headB!=NULL){
if(headA==headB){
return headA;
}
headA=headA->next;
headB=headB->next;
}
return NULL;
}
};