-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersectionInLinkedList.cpp
More file actions
59 lines (50 loc) · 1.36 KB
/
intersectionInLinkedList.cpp
File metadata and controls
59 lines (50 loc) · 1.36 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* 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) {
if(!headA || !headB) return NULL;
int lenA =0;
int lenB =0;
ListNode* currA = headA, *currB = headB;
while(currA || currB){
if(currA){
lenA++;
currA = currA->next;
}
if(currB){
lenB++;
currB = currB->next;
}
}
currA= headA; currB = headB;
if(lenA > lenB){
int cnt = lenA-lenB;
while(cnt>0){
currA = currA->next;
cnt--;
}
}
else{
int cnt = lenB-lenA;
while(cnt>0){
currB = currB->next;
cnt--;
}
}
while(currA && currB){
if(currA->val == currB->val){
return currA;
}
currA = currA->next;
currB = currB->next;
}
return NULL;
}
};