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

Commit e511c2e

Browse files
author
Ram swaroop
committed
intersection of 2 sorted list done
1 parent a9acb8d commit e511c2e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 6/27/15
11+
* @time: 11:13 AM
12+
*/
13+
public class IntersectionOf2SortedLists<E extends Comparable<E>> extends SingleLinkedList<E> {
14+
15+
/**
16+
* Returns a linked list with elements common in
17+
* both {@param list1} and {@param list2}.
18+
*
19+
* @param list1
20+
* @param list2
21+
* @param <E>
22+
* @return
23+
*/
24+
public static <E extends Comparable<E>> SingleLinkedList<E> getIntersectionList(SingleLinkedList<E> list1,
25+
SingleLinkedList<E> list2) {
26+
27+
SingleLinkedNode<E> curr1 = list1.getNode(0), curr2 = list2.getNode(0);
28+
SingleLinkedList<E> intersectedList = new SingleLinkedList<>();
29+
while (curr1 != null && curr2 != null) {
30+
// advance the current pointer of the list having smaller {@code item}
31+
if (curr1.item.compareTo(curr2.item) < 0) {
32+
curr1 = curr1.next;
33+
} else if (curr1.item.compareTo(curr2.item) > 0) {
34+
curr2 = curr2.next;
35+
} else { // both nodes are equal so add it to the result
36+
intersectedList.add(curr1.item);
37+
curr1 = curr1.next;
38+
curr2 = curr2.next;
39+
}
40+
}
41+
42+
return intersectedList;
43+
}
44+
45+
public static void main(String a[]) {
46+
SingleLinkedList<Integer> linkedList1 = new SingleLinkedList<>();
47+
linkedList1.add(00);
48+
linkedList1.add(11);
49+
linkedList1.add(22);
50+
linkedList1.add(33);
51+
linkedList1.add(44);
52+
linkedList1.add(55);
53+
linkedList1.printList();
54+
SingleLinkedList<Integer> linkedList2 = new SingleLinkedList<>();
55+
linkedList2.add(21);
56+
linkedList2.add(33);
57+
linkedList2.add(44);
58+
linkedList2.add(55);
59+
linkedList2.add(67);
60+
linkedList2.add(89);
61+
linkedList2.printList();
62+
getIntersectionList(linkedList1, linkedList2).printList();
63+
}
64+
}

0 commit comments

Comments
 (0)