So what I am trying to do is to sort linked list. I’m stuck on breaking out of the loop where it seems that it never escapes. From examples I found all I had to do is to check if next value would be null, so what am I doing wrong?
Also, since I can’t figure out why this won’t brake out of loop, does this code seems like should do linked list sorting correctly?
public void sortFirst() {
do
{
if (first.iData >= first.next.iData)
{
int iTempData = first.iData;
double dTempData = first.dData;
first.iData = first.next.iData;
first.dData = first.next.dData;
Link newLink = new Link(iTempData, dTempData);
newLink.next = first;
first = newLink;
}
}
while (first.next != null);
}
Well, right off the bat, you have a logic problem in your last 3 lines:
Here, you set newLink.next = first. Therefore it isn’t null. Next you set first = newLink. So you can quickly see that first.next will never be null.
From what I can tell in your loop, you are not actually shifting nodes around in your list,
but only data within the nodes. In which case, you only need to move the data around:
(and remove the last 3 lines which create the new node and insert it incorrectly in the list).
Of course, that is a little ugly. The cool things with linked lists is that you can simply move the nodes around in your list, so you would do something like the following: