1
1
package me .ramswaroop .linkedlists ;
2
2
3
3
import me .ramswaroop .common .SingleLinkedList ;
4
+ import me .ramswaroop .common .SingleLinkedNode ;
4
5
5
6
/**
6
7
* Created by IntelliJ IDEA.
11
12
*/
12
13
public class IntersectionAndUnionOf2Lists {
13
14
15
+ /**
16
+ *
17
+ * @param list1
18
+ * @param list2
19
+ * @param <E>
20
+ * @return an array of list consisting of intersection and union of {@param list1} and {@param list2} respectively.
21
+ */
14
22
public static <E extends Comparable <E >> SingleLinkedList <E >[] getIntersectionAndUnion (SingleLinkedList <E > list1 ,
15
23
SingleLinkedList <E > list2 ) {
16
24
25
+ SingleLinkedNode <E > curr1 = list1 .head , curr2 = list2 .head ;
26
+ SingleLinkedList <E > intersectionList = new SingleLinkedList <>(),
27
+ unionList = new SingleLinkedList <>();
17
28
29
+ MergeSort .mergeSort (curr1 );
30
+ MergeSort .mergeSort (curr2 );
18
31
19
- return null ;
32
+ while (curr1 != null || curr2 != null ) {
33
+ if (curr1 == null ) {
34
+ unionList .add (curr2 .item );
35
+ curr2 = curr2 .next ;
36
+ } else if (curr2 == null ) {
37
+ unionList .add (curr1 .item );
38
+ curr1 = curr1 .next ;
39
+ } else if (curr1 .item .compareTo (curr2 .item ) < 0 ) {
40
+ unionList .add (curr1 .item );
41
+ curr1 = curr1 .next ;
42
+ } else if (curr1 .item .compareTo (curr2 .item ) > 0 ) {
43
+ unionList .add (curr2 .item );
44
+ curr2 =curr2 .next ;
45
+ } else {
46
+ unionList .add (curr1 .item );
47
+ intersectionList .add (curr1 .item );
48
+ curr1 = curr1 .next ;
49
+ curr2 = curr2 .next ;
50
+ }
51
+ }
52
+
53
+ return new SingleLinkedList []{intersectionList , unionList };
20
54
}
21
55
22
56
public static void main (String a []) {
@@ -36,7 +70,9 @@ public static void main(String a[]) {
36
70
linkedList2 .add (67 );
37
71
linkedList2 .add (89 );
38
72
linkedList2 .printList ();
73
+ System .out .println ("Intersection:" );
39
74
getIntersectionAndUnion (linkedList1 , linkedList2 )[0 ].printList ();
75
+ System .out .println ("Union:" );
40
76
getIntersectionAndUnion (linkedList1 , linkedList2 )[1 ].printList ();
41
77
}
42
78
}
0 commit comments