Skip to content

Commit 259d1b9

Browse files
committed
Added Code for Find Intersection of 2 Linked List [Problem 160 of LeetCode]
1 parent 74efb75 commit 259d1b9

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
3+
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
4+
5+
6+
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
7+
Output: Intersected at '8'
8+
9+
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
10+
Output: Intersected at '2'
11+
12+
Constraints:
13+
14+
> The number of nodes of listA is in the m.
15+
> The number of nodes of listB is in the n.
16+
> 1 <= m, n <= 3 * 104
17+
> 1 <= Node.val <= 105
18+
> 0 <= skipA < m
19+
> 0 <= skipB < n
20+
> intersectVal is 0 if listA and listB do not intersect.
21+
> intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.
22+
23+
*/
24+
25+
/**
26+
* Definition for singly-linked list.
27+
* struct ListNode {
28+
* int val;
29+
* ListNode *next;
30+
* ListNode(int x) : val(x), next(NULL) {}
31+
* };
32+
*/
33+
class Solution {
34+
public:
35+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
36+
// Define basic variables needed
37+
int len1=0;
38+
int len2=0;
39+
ListNode* tempA=headA;
40+
ListNode* tempB=headB;
41+
42+
// Calculate the length of both Linked Lists and store in len1 and len2
43+
while(tempA!=NULL)
44+
{
45+
len1++;
46+
tempA=tempA->next;
47+
}
48+
while(tempB!=NULL)
49+
{
50+
len2++;
51+
tempB=tempB->next;
52+
}
53+
54+
// Here, we assume that length of Linked-List A is less than or equal
55+
// to that of Linked List B
56+
if(len1>len2){
57+
swap(headA,headB);
58+
}
59+
60+
// Re-initialize variables
61+
tempA=headA;
62+
tempB=headB;
63+
int n=abs(len2-len1);
64+
while(n--)
65+
{
66+
tempB=tempB->next;
67+
}
68+
69+
// Finally, Find the Intersection Node
70+
while(tempA!=tempB)
71+
{
72+
tempA=tempA->next;
73+
tempB=tempB->next;
74+
}
75+
76+
// Return the final answer
77+
return tempA;
78+
}
79+
};

0 commit comments

Comments
 (0)