I’m trying to insert 2 numbers into linked list. The list must be ordered so smaller number must be inserted before larger one.
The list first adds larger number and then when inserting second, smaller, number it must swap larger with smaller.
I created this method just to do that, the problem in this code is that it first adds larger number, then smaller number and then, once again, larger number.
What am I doing wrong?
public void insertFirst(int id, double dd)
{
if (isEmpty())
{
Link newLink = new Link(id, dd);
newLink.next = first;
first = newLink;
}
else
{
if (first.iData < id)
{
Link newLink = new Link(id, dd);
newLink.next = first;
first = newLink;
}
else
{
int iTempData = first.iData;
double dTempData = first.dData;
Link newLink = new Link(id, dd);
newLink.next = first;
first = newLink;
Link newLink2 = new Link(iTempData, dTempData);
newLink2.next = first;
first = newLink2;
}
}
}
A quick fix would be
Note that this function doesn’t actually maintain the list sorted — it can add the new item as either the first or the second, but what if the passed ID is greater than all (say ten) items already in the list?