I have been asked to create a method to merge two LinkedList.
I am allowed to use only the following methods:
From LinkedList:
> addLast(E);
> size();
From ListIterator:
> E next();
> boolean hasNext();
> E previous();
> void remove();
The first list (list1) points to 2,6,7
The second list (list2) points to 3,5,8
--> After the creation of the merge list the two lists must be empty.
Here is my code:
Class SortedLinkedList:
import java.util.*;
public class SortedLinkedList<E extends Comparable<? super E>> extends LinkedList<E>
{
@SuppressWarnings("unchecked")
public void mergeLists(SortedLinkedList<E> list1, SortedLinkedList<E> list2)
{
ListIterator<E> itr1 = list1.listIterator(); //List Iterator for the first list
ListIterator<E> itr2 = list2.listIterator(); //List Iterator for the second list
while(itr1.hasNext() || itr2.hasNext())
{
E item1 = null; //variable to first node in first list
E item2 = null; //variable to first node in second list
if(itr1.hasNext())
{
item1 = itr1.next();
}
if(itr2.hasNext())
{
item2 = itr2.next();
}
if(item1 == null)
{
while(list2 != null)
{
item1 = itr2.next();
}
}
else if(item2 == null)
{
while(list1 != null)
{
item2 = itr1.next();
}
}
else if(item1.compareTo(item2) < 0)
{
addLast(item1);
((ListIterator<E>) item1).next();
((LinkedList<E>) item1).remove();
}
else
{
addLast(item2);
((ListIterator<E>) item2).next();
((LinkedList<E>) item2).remove();
}
}
}
}
Class TestMergeList:
import java.util.*;
public class TestMergeList
{
public static void main(String[] args)
{
SortedLinkedList<Integer> list1 = new SortedLinkedList<Integer>();
SortedLinkedList<Integer> list2 = new SortedLinkedList<Integer>();
SortedLinkedList<Integer> newList = new SortedLinkedList<Integer>();
list1.addLast(2);
list1.addLast(6);
list1.addLast(7);
list2.addLast(3);
list2.addLast(5);
list2.addLast(8);
newList.mergeLists(list1,list2);
}
}
Compiler points to the following errors:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.ListIterator
at SortedLinkedList.mergeLists(SortedLinkedList.java:41)
at TestMergeList.main(TestMergeList.java:19)
I appreciate any help.