-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindIntersection.java
More file actions
91 lines (74 loc) · 2.17 KB
/
findIntersection.java
File metadata and controls
91 lines (74 loc) · 2.17 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
}
}
public class findIntersection {
public static Node Intersection(Node head1, Node head2){
TreeSet<Integer> set = new TreeSet<>();
Node temp = head1;
while(temp!=null){
set.add(temp.data);
temp = temp.next;
}
TreeSet<Integer> ans = new TreeSet<>();
temp = head2;
while(temp!=null){
if(set.contains(temp.data)){
ans.add(temp.data);
}
temp = temp.next;
}
Node dummy = new Node(0);
Node curr = dummy;
for(int x : ans){
curr.next = new Node(x);
curr = curr.next;
}
return dummy.next;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (!sc.hasNextInt()) return;
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
Node head1 = null, tail1 = null;
for (int i = 0; i < n; i++) {
int val = sc.nextInt();
Node newNode = new Node(val);
if (head1 == null) {
head1 = newNode;
tail1 = newNode;
} else {
tail1.next = newNode;
tail1 = newNode;
}
}
int m = sc.nextInt();
Node head2 = null, tail2 = null;
for (int i = 0; i < m; i++) {
int val = sc.nextInt();
Node newNode = new Node(val);
if (head2 == null) {
head2 = newNode;
tail2 = newNode;
} else {
tail2.next = newNode;
tail2 = newNode;
}
}
Node res = Intersection(head1, head2);
while (res != null) {
System.out.print(res.data + " ");
res = res.next;
}
System.out.println();
}
sc.close();
}
}