In: Computer Science
Write Java code for extending the LinkedList<E> class of java.util.* to ExtLinkedList<E> that would include the following method:
public ExtLinkedList <E> mergeThreeLists (ExtLinkedList<E> list1, ExtLinkedList<E> list2) {
}
that returns an ExtLinkedList<E> which is the merged version of values from thislist, followed by values from list1, and then followed by values from list2. For example, if E is Integer type and this listhas (5,3,1), list1has (8, 10,12,14), and list2has (22,23,24,25,26) in that order, then the returned list from a call to list.mergeThreeLists(list1,list2) will have (5,3,1,8,10,12,14,22,23,24, 25,26). Obviously the size of the returned list will be equal to list.size()+list1.size()+list2.size(). Use listIterator() to do this efficiently for full credit. Your code should work for any size including the empty list and any parameter E.
is there an applicable code? if so, what is it?
If you have any problem with the code feel free to comment.
Program
import java.util.Iterator;
import java.util.LinkedList;
class ExtLinkedList<E> extends LinkedList<E> {
public ExtLinkedList<E> mergeThreeLists(ExtLinkedList<E> list1, ExtLinkedList<E> list2) {
// empty list
ExtLinkedList<E> ll = new ExtLinkedList<>();
// calculating the size of the merged list
int size = this.size() + list1.size() + list2.size();
// creating iterators
Iterator<E> i1 = this.iterator();
Iterator<E> i2 = list1.iterator();
Iterator<E> i3 = list2.iterator();
// main loop
for (int i = 0; i < size; i++) {
// adding data from the list
if (i1.hasNext())
ll.add(i1.next());
else if (i2.hasNext())
ll.add(i2.next());
else if (i3.hasNext())
ll.add(i3.next());
}
return ll;
}
}
public class Test {
public static void main(String[] args) {
// testing the code
ExtLinkedList<Integer> list = new ExtLinkedList<>();
list.add(5);
list.add(3);
list.add(1);
ExtLinkedList<Integer> list1 = new ExtLinkedList<>();
list1.add(8);
list1.add(10);
list1.add(12);
list1.add(14);
ExtLinkedList<Integer> list2 = new ExtLinkedList<>();
list2.add(22);
list2.add(23);
list2.add(24);
list2.add(25);
list2.add(26);
System.out.println(list.mergeThreeLists(list1, list2));
}
}
Output