Question

I am attempting to insert people alphabetically into a linked list by lastName. I have one really weird issue. The code as you see it works fine, except the list is in reverse order. What I can not figure out is why when I use the line of code:

    current != null && lastName.compareTo(current.lastName) >= 0)

to insert people into my list, instead of adding over 100 people I add 6. Yet like I said above I can do it in reverse order no problem. What is up with that?

    public void insert(String firstName, String lastName, String time,String show, String      command,int section){
    PeopleNode newNode = new PeopleNode(lastName,firstName,time,show,command,section);
    size++;
    PeopleNode previous = null;
    PeopleNode current = head;

    while(current != null && lastName.compareTo(current.lastName) <= 0){
        previous = current;
        current = current.next;
    }

    if(previous == null){
        head = newNode;
    }else{
        previous.next = newNode;
        newNode.next = current;
    }
}
Was it helpful?

Solution

I guess the compareTo method works the other way round for Strings, so maybe try

while(current != null && current.lastName.compareTo(lastName) <= 0)

But I recommend you to use just the Compareable interface and sort the list by using Collections.sort(yourlist)

OTHER TIPS

Let's say you have "b", "c", "d" and "a" as the last names. If you insert in that order, for the first three nodes it will be:

b -> c -> d

When you try to insert a, it will not enter the while loop. So, "previous" will be null. It will enter the first if condition and set the head as the new node, i.e. "a", and it will exit the method. Next of the head is not set.

So you have a broken list with only the "a" node at the end.

I did not try this but this seems to be the problem.

Ok I figured it out!

if(previous == null){
    head = newNode;
}else{
    previous.next = newNode;
    newNode.next = current;
}

The line:

 newNode.next = current;

needs to be outside of the else statement!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top