【问题标题】:How to sort a linked list with objects in java如何在java中对带有对象的链表进行排序
【发布时间】:2013-02-13 11:22:24
【问题描述】:

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

容器:

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-method 来检查对象的放置位置,但我不确定应该如何设置链表的结构。我已经开始这样做了:

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

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

【问题讨论】:

  • 有什么理由不能使用 TreeSet 代替吗? docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html
  • 如果你需要一个链表,你可以使用 java.util.LinkedList,如果你需要一个按键排序的 Map,你可以使用 java.util.TreeMap 。我认为 TreeMap 可以满足您的需求。
  • @anoopelias 可能他必须自己实现它,例如就像作业一样。
  • 我建议使用 Java 约定,以小写字母开头方法,并避免使用国家语言字符。

标签: java list sorting linked-list compareto


【解决方案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++;
}

这将使您的列表保持有序。

【讨论】:

  • 这正是我想要的。非常感谢!
【解决方案2】:
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2012-04-26
  • 2019-09-05
  • 2016-03-21
相关资源
最近更新 更多