1

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!

1
  • 1
    I see 2 problems with it as is: 1) I think you need to reverse your first 2 elseifs since your not covering the case where head.next is null, but newelem.value is greater than head.value. 2) in you're final else if you shouldn't reassign the head. Commented Apr 11, 2013 at 3:10

3 Answers 3

1

The head = head.next statement in your fourth conditional block is destroying the head element. I believe this should instead be

else if(head.value >= newelem.value) {
    head.next = InsertList(head.next, newelem);
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you try to insert 15, you enter the 4th condition:

// 20 > 15
else if (head.value >= newelem.value)

which in turn calls InsertList but passes 8 as the head node and thus enters the 3rd condition:

// 8 < 15
else if (head.value < newelem.value) 

Here, you say

newelem.next = head;

which sets 15 -> next = 8

and then you say,

head = newelem;

which sets head = 15.

Do you see the problem? Use @Zim-Zam O'Pootertoot answer to fix your bug.

Comments

0

Thanks for all the help and answers guys!
I found another post similar to mine and one of the answers on there seemed to work for me.
Here is the link for anyone who wishes to see: https://stackoverflow.com/a/15936744/1470257

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.