如何使用java中的对象对链表进行排序

时间:2013-02-27 15:20:25

标签: java list sorting linked-list compareto

我已经用Java中的对象创建了一个链表(通用容器)。我需要重新编写我的insert方法,使列表按键按字母顺序排序。到目前为止,这是我的代码:

容器:

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;
    }
}

这是我的插入方法(我需要重写):

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

这是Person-object,我把它放在容器(链表)中:

class Person {

    String name;

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

这就是我创造人并将其放入容器的方式:

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

任何帮助都会让我非常感激。我知道我需要使用CompareTo-metohod来检查放置对象的位置,但我不确定应该如何设置链表的结构。我已经开始了:

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

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

2 个答案:

答案 0 :(得分:1)

在列表中迭代,直到找到合适的位置:

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++;
}

这会保留您的清单。

答案 1 :(得分:0)