public void setIntersection(LinkList list1, LinkList list2) {
LinkList list4 = new LinkList();
Node a = list1.head;
Node b = list2.head;
while (a != null && b != null) {
if (a.value < b.value) {
a = a.next;
} else if (a.value > b.value) {
b = b.next;
} else if (a.value == b.value){
list4.insert(a.value);
a = a.next;
b = b.next;
}
}
list4.printList();
}
I want to find out the common values appearing in List 1 and List 2 and save the entries in List4. Although this seems straight forward, I still feel my code is too long and wondering if there is a more efficient way to solve this problem ?
1 Answer