I have a LinkedList of ListElement objects, and I would like to create a recursive method that adds new nodes while still preserving the sorted order of the list.
Right now I have:
public static ListElement InsertList(ListElement head, ListElement newelem) {
if (head == null) {
head = newelem;
head.next = null;
}
else if (head.next == null) {
newelem.next = null;
head.next = newelem;
}
else if (head.value < newelem.value) {
newelem.next = head;
head = newelem;
}
else if (head.value >= newelem.value) {
head = head.next;
return InsertList(head, newelem);
}
return head;
}
And I am calling it multiple times with the code:
ListElement head = null;
ListElement elem;
// this block of code is repeated multiple times with values of 3, 8, 20, and 15
elem - new ListElement();
elem.value = 6;
head = InsertList( head, elem );
The output is as follows:
6
6 3
8 6 3
20 8 6 3
15 8 6 3
This output is correct for the first three lines, but after that it all goes weird. Can anyone please improve my algorithm? I feel like the InsertList method could be shortened a lot more. Thanks!