Skip to content

Commit f80d980

Browse files
committed
Runtime: 101 ms (Top 23.35%) | Memory: 14.3 MB (Top 98.77%)
1 parent 57caa6c commit f80d980

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,76 @@
1+
// Runtime: 101 ms (Top 23.35%) | Memory: 14.3 MB (Top 98.77%)
12
/**
23
* Definition for singly-linked list.
34
* 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) {}
78
* };
89
*/
910
class Solution {
1011
public:
11-
12+
1213
//function to get length of linked list
1314
int getLength(ListNode *head)
1415
{
1516
//initial length 0
1617
int l = 0;
17-
18+
1819
while(head != NULL)
1920
{
2021
l++;
2122
head = head->next;
2223
}
2324
return l;
2425
}
25-
26+
2627
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
27-
28+
2829
//ptr1 & ptr2 will move to check nodes are intersecting or not
2930
//ptr1 will point to the list which have higher length, higher elements (big list)
3031
//ptr2 will point to small list
3132
ListNode *ptr1,*ptr2;
32-
33+
3334
//fetching length of both the list,as we want a node that both ptr points simultaneously
3435
//so if both list have same length of nodes, they travel with same speed, they intersect
3536
//if diff legths, it'll be difficult for us to catch
3637
//so by substracting list with higher length with lower length
3738
//we get same level of length, from which both ptr start travaeling, they may get intersect
3839
int length1 = getLength(headA);
3940
int length2 = getLength(headB);
40-
41+
4142
int diff = 0;
42-
43+
4344
//ptr1 points to longer list
4445
if(length1>length2)
4546
{
4647
diff = length1-length2;
4748
ptr1 = headA;
4849
ptr2 = headB;
49-
50+
5051
}
5152
else
5253
{
5354
diff = length2 - length1;
5455
ptr1 = headB;
5556
ptr2 = headA;
5657
}
57-
58+
5859
//till diff is zero and we reach our desired posn
5960
while(diff)
6061
{
6162
//incrementing ptr1 so that it can be at a place where both list have same length
62-
63+
6364
ptr1 = ptr1->next;
64-
65+
6566
if(ptr1 == NULL)
6667
{
6768
return NULL;
6869
}
69-
70+
7071
diff--;
7172
}
72-
73+
7374
//traverse both pointers together, till any of them gets null
7475
while((ptr1 != NULL) && (ptr2 != NULL))
7576
{
@@ -78,14 +79,14 @@ class Solution {
7879
{
7980
return ptr1;
8081
}
81-
82+
8283
//increment both pointers, till they both be NULL
8384
ptr1 = ptr1->next;
8485
ptr2 = ptr2->next;
8586
}
86-
87+
8788
//if not found any intersaction, return null
8889
return NULL;
89-
90+
9091
}
9192
};

0 commit comments

Comments
 (0)