1
+ // Runtime: 101 ms (Top 23.35%) | Memory: 14.3 MB (Top 98.77%)
1
2
/* *
2
3
* Definition for singly-linked list.
3
4
* struct ListNode {
4
- * int val;
5
- * ListNode *next;
6
- * ListNode(int x) : val(x), next(NULL) {}
5
+ * int val;
6
+ * ListNode *next;
7
+ * ListNode(int x) : val(x), next(NULL) {}
7
8
* };
8
9
*/
9
10
class Solution {
10
11
public:
11
-
12
+
12
13
// function to get length of linked list
13
14
int getLength (ListNode *head)
14
15
{
15
16
// initial length 0
16
17
int l = 0 ;
17
-
18
+
18
19
while (head != NULL )
19
20
{
20
21
l++;
21
22
head = head->next ;
22
23
}
23
24
return l;
24
25
}
25
-
26
+
26
27
ListNode *getIntersectionNode (ListNode *headA, ListNode *headB) {
27
-
28
+
28
29
// ptr1 & ptr2 will move to check nodes are intersecting or not
29
30
// ptr1 will point to the list which have higher length, higher elements (big list)
30
31
// ptr2 will point to small list
31
32
ListNode *ptr1,*ptr2;
32
-
33
+
33
34
// fetching length of both the list,as we want a node that both ptr points simultaneously
34
35
// so if both list have same length of nodes, they travel with same speed, they intersect
35
36
// if diff legths, it'll be difficult for us to catch
36
37
// so by substracting list with higher length with lower length
37
38
// we get same level of length, from which both ptr start travaeling, they may get intersect
38
39
int length1 = getLength (headA);
39
40
int length2 = getLength (headB);
40
-
41
+
41
42
int diff = 0 ;
42
-
43
+
43
44
// ptr1 points to longer list
44
45
if (length1>length2)
45
46
{
46
47
diff = length1-length2;
47
48
ptr1 = headA;
48
49
ptr2 = headB;
49
-
50
+
50
51
}
51
52
else
52
53
{
53
54
diff = length2 - length1;
54
55
ptr1 = headB;
55
56
ptr2 = headA;
56
57
}
57
-
58
+
58
59
// till diff is zero and we reach our desired posn
59
60
while (diff)
60
61
{
61
62
// incrementing ptr1 so that it can be at a place where both list have same length
62
-
63
+
63
64
ptr1 = ptr1->next ;
64
-
65
+
65
66
if (ptr1 == NULL )
66
67
{
67
68
return NULL ;
68
69
}
69
-
70
+
70
71
diff--;
71
72
}
72
-
73
+
73
74
// traverse both pointers together, till any of them gets null
74
75
while ((ptr1 != NULL ) && (ptr2 != NULL ))
75
76
{
@@ -78,14 +79,14 @@ class Solution {
78
79
{
79
80
return ptr1;
80
81
}
81
-
82
+
82
83
// increment both pointers, till they both be NULL
83
84
ptr1 = ptr1->next ;
84
85
ptr2 = ptr2->next ;
85
86
}
86
-
87
+
87
88
// if not found any intersaction, return null
88
89
return NULL ;
89
-
90
+
90
91
}
91
92
};
0 commit comments