-
Notifications
You must be signed in to change notification settings - Fork 5
/
IntersectionOfLists.java
44 lines (39 loc) · 1.02 KB
/
IntersectionOfLists.java
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
/*https://practice.geeksforgeeks.org/problems/intersection-of-two-linked-list/1*/
class Solution
{
public static Node findIntersection(Node head1, Node head2)
{
HashSet<Integer> set = new HashSet<Integer>();
//add second list to hashset
while (head2 != null)
{
set.add(head2.data);
head2 = head2.next;
}
//move till the first intersection point
Node prev = head1;
while (!set.contains(head1.data))
{
prev = head1;
head1 = head1.next;
}
//move till the end of first list
Node temp = head1;
while (temp != null)
{
//if intersection then move
if (set.contains(temp.data))
{
prev = temp;
temp = temp.next;
}
//otherwise delete
else
{
prev.next = temp.next;
temp = prev.next;
}
}
return head1;
}
}