-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path60. Intersection of Two Linked Lists.cpp
85 lines (72 loc) · 1.82 KB
/
60. 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
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
int findLength(ListNode* head)
{
int cnt = 0;
while(head != NULL)
{
head = head -> next;
cnt++;
}
return cnt;
}
ListNode* intersection(ListNode* smaller, ListNode* longer, int diff)
{
//traverse the longest list to make them on same level
for(int i=0; i<diff; i++)
{
longer = longer -> next;
}
while(longer && smaller)
{
if(longer == smaller)
{
return longer;
}
longer = longer -> next;
smaller = smaller -> next;
}
return NULL;
}
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
/* first approach */
// int l1 = findLength(headA);
// int l2 = findLength(headB);
// if(l1 > l2) //pass smaller list, bigger list and diff of size
// {
// return intersection(headB, headA, l1 - l2);
// }
// else{
// return intersection(headA, headB, l2 - l1);
// }
/* second approach */
ListNode* temp1 = headA;
ListNode* temp2 = headB;
while(temp1 && temp2)
{
if (temp1 == temp2) {
return temp1;
}
temp1 = temp1 -> next;
temp2 = temp2 -> next;
if(temp1 == NULL && temp2 == NULL)
return NULL;
if (temp1 == NULL){
temp1 = headB;
}
if(temp2 == NULL){
temp2 = headA;
}
}
return NULL;
}
};