Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2a90631

Browse files
author
Ram swaroop
committed
intersection and union of linked list: done
1 parent c2badc3 commit 2a90631

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

src/me/ramswaroop/linkedlists/IntersectionAndUnionOf2Lists.java

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package me.ramswaroop.linkedlists;
22

33
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
45

56
/**
67
* Created by IntelliJ IDEA.
@@ -11,12 +12,45 @@
1112
*/
1213
public class IntersectionAndUnionOf2Lists {
1314

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+
*/
1422
public static <E extends Comparable<E>> SingleLinkedList<E>[] getIntersectionAndUnion(SingleLinkedList<E> list1,
1523
SingleLinkedList<E> list2) {
1624

25+
SingleLinkedNode<E> curr1 = list1.head, curr2 = list2.head;
26+
SingleLinkedList<E> intersectionList = new SingleLinkedList<>(),
27+
unionList = new SingleLinkedList<>();
1728

29+
MergeSort.mergeSort(curr1);
30+
MergeSort.mergeSort(curr2);
1831

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};
2054
}
2155

2256
public static void main(String a[]) {
@@ -36,7 +70,9 @@ public static void main(String a[]) {
3670
linkedList2.add(67);
3771
linkedList2.add(89);
3872
linkedList2.printList();
73+
System.out.println("Intersection:");
3974
getIntersectionAndUnion(linkedList1, linkedList2)[0].printList();
75+
System.out.println("Union:");
4076
getIntersectionAndUnion(linkedList1, linkedList2)[1].printList();
4177
}
4278
}

0 commit comments

Comments
 (0)