I have been asked to design a method splitMid that can be added to the LinkedList<E> class.
This method should have the following header:
public void splitMid(LinkedList<E> sublist)
and should split the given list into two sub-lists of (almost) equal sizes. Suppose myList points to the with elements 34,65,27,89 and 12. The statement myList.splitMid(sublist); should split myList into two sublists: myList --> 34,65 and 27
sublist --> 89,12
----------------------------------------------------------------------------------------
I have made the foolwing assumptions:
1)The head of a linkedlist always points to the first node.
2)Create a new head pointer for the second linkedlist.
3)Traverse through the linkedlist and find where you want to split the list and assign the pointer to that node variable midPoint and set the next pointer of previous node to null.
I have aome problems to complete this task. Any suggestions and guidelines would be appreciated.
Here is my code:
class SplitLinkedList:
import java.util.LinkedList;
public class SplitLinkedList<E> {
public void splitMid(LinkedList<E> sublist)
{
Node midPoint = nodeBefore.next; // get the midpoint
LinkedList n = new LinkedList();
n.head = midPoint; // head pointer for the second linked list
for(int i = 0; i < n.size(); ++i)
{
}
}
}
class TestSplitLinkedList:
import java.util.LinkedList;
public class TestSplitLinkedList<E> {
public void main(String args[])
{
LinkedList<Integer> myList = new LinkedList<Integer>();
SplitLinkedList sublist = new SplitLindedList();
myList.addLast(34);
myList.addLast(65);
myList.addLast(27);
myList.addLast(89);
myList.addLast(12);
myList.splitMid(sublist);
}
}