Search code examples
javalistsortinglinked-listcompareto

How to sort a linked list with objects in java


I've created a linked list (generic containers) with objects in Java. I need to re-write my insert-method to make the list sorted alphabetically by keys. This is my code so far:

Container:

class Sellbeholder<N extends Comparable<N>, V> implements INF1010samling<N,V> {

private Keeper første;
private int ant = 0;

private class Keeper {
    Keeper neste;
    N n;
    V v;

    Keeper(N n,V v) {
        this.n = n;
        this.v = v;
    }
}

This is my insert method (which I need to rewrite):

public void PutIn(N n, V v) {
    Keeper kep = new Keeper(n,v);
    kep.neste = første;
    første = kep;
    ant++;

This is the Person-object, which I'm putting in the container(linked list):

class Person {

    String name;

    Person(String n) {
        this.name = n;
    }
}

And this is how I create persons and put them in container:

Sellbeholder <String,Person> b1 = new Sellbeholder <String,Person>();
Person a = new Person("William");
b1.PutIn("William",a);

Any help would me much appreciated. I know I need to use the CompareTo-metohod to check where to put the object, but I'm not sure how the structure of the linked list should be set. I've started on this:

for(Keeper nn = første; nn!= null; nn = nn.neste) {

    if(nn.n.compareTo(kep.n) > 0) {
        //Do something here

Solution

  • Iterate on the list until you get the proper place:

    public void PutIn(N n, V v) {
        Keeper kep = new Keeper(n,v);
        // you will insert between previous and current
        Keeper previous = null;
        Keeper current = første;
    
        // loop until you get the right place        
        while (current != null && ((current.n).compareTo(n) > 0)) {
            previous = current;
            current = current.neste;
        }
    
        // insert your stuff there (if there were no previous, then this is the first one)
        if (previous == null) {
            første = kep;
        } else {
            previous.neste = kep;
        }
    
        // Set the next Keeper
        kep.neste = current;
    
        ant++;
    }
    

    This will keep your list ordered.