-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day_66.cpp
69 lines (54 loc) · 1.53 KB
/
Day_66.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
/*
DAY 66 : Intersection Point in Y Shapped Linked Lists.
https://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/
QUESTION : Given two singly linked lists of size N and M, write a program to get the point where
two linked lists intersect each other.
Example:
Input:
LinkList1 = 3->6->9->common
LinkList2 = 10->common
common = 15->30->NULL
Output: 15
Expected Time Complexity : O(N+M)
Expected Auxilliary Space : O(1)
Constraints:
1 ≤ N + M ≤ 2*10^5
-1000 ≤ value ≤ 1000
*/
int intersectPoint(Node* head1, Node* head2)
{
// Your Code Here
int count_1 = 0;
int count_2 = 0;
Node* current1 = head1;
Node* current2 = head2;
while(current1 != NULL) {
count_1+=1;
current1 = current1->next;
}
while(current2 != NULL) {
count_2+=1;
current2 = current2->next;
}
int diff = abs(count_1 - count_2);
current1 = head1;
current2 = head2;
if (count_1 > count_2) {
for (int i = 0; i < diff; i++) {
current1 = current1->next;
}
}
else if (count_2 > count_1) {
for (int i = 0; i < diff; i++) {
current2 = current2->next;
}
}
while(current1 != NULL && current2 != NULL) {
if (current1 == current2) {
return current1->data;
}
current1 = current1->next;
current2 = current2->next;
}
return -1;
}