I am a beginner, below is the best that I could come up so far. The objective of the method .Split() is that I am supposed to rearrange (rearrange only, no adding or removing nodes nor switching data of the nodes) the elements of the LinkedIntList <- This is not that standard LinkedList class, its a modified class that I have to use, there is no Java method that I can use for this problem unfortunately.
For example, if a linkedlist is [1, 5, -9, 7, -5, 78], the result should be [-9,-5, 1, 5, 7, 78]. The order of the negative values do not matter.
There is only one private field, which is ListNode front;
I am trying to use current.data < 0
to pick out the negative values and put them at the front of the list, iterating from the front, and start over. Making sure that it selects all the negative values from the list. But my output keeps getting stuck in a endless loop, unable to break. I am not sure what to do here.
Here is my best attempt at this problem.
public void Split()
{
ListNode current = front;
ListNode head = front;
while (current.next != null)
{
if (current.data < 0)
{
current.next = front; // set the pointer of current's node
front = current; // update the head with a negative value
current = current.next; // iterate from the front
}
else if (current.data >= 0)
{
current = current.next; // if positive, skip the process and keep iterating
}
else
{
break; // break if null or anything else
}
if (current.next == null || current == null)
{
break; // another attempt to break since it keeps getting stuck
}
}
}