我用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方法来检查放置对象的位置,但我不确定应该如何设置链表的结构。我已经开始了:
for(Keeper nn = første; nn!= null; nn = nn.neste) {
if(nn.n.compareTo(kep.n) > 0) {
//Do something here
遍历列表,直到找到合适的位置:
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++;
}
尝试使用集合。sort(List 1)或Collections。sort(List 1, Comparator c)