-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160. Intersection of two linked lists.cpp
73 lines (55 loc) · 1.45 KB
/
160. Intersection of two linked lists.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* 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)
return NULL;
if(!headB)
return NULL;
int na = 0;
int nb = 0;
ListNode *cur = headA;
while(cur) {
cur = cur->next;
na++;
}
cur = headB;
while(cur) {
cur = cur->next;
nb++;
}
ListNode *a, *b;
int diff = abs(na-nb);
if (na > nb) {
a = headA;
b = headB;
}
else {
a = headB;
b = headA;
}
while(a && diff--) {
a = a->next;
}
while(a && b) {
if (a->val == b->val)
return a;
a = a->next;
b = b->next;
}
return NULL;
}
};
// Smarter solution: traverse both at the same time without calculating the
// individual lengths.
// If A's end is reached then point it to B and if B's end is reached then point it
// to head of A. In the second traversal they are guaranteed to collide if there is
// an intersection
// https://discuss.leetcode.com/topic/5527/my-accepted-simple-and-shortest-c-code-with-comments-explaining-the-algorithm-any-comments-or-improvements