【发布时间】:2016-06-09 15:20:02
【问题描述】:
我已经构建了一个由Friend 对象组成的多链表。 Friend 类具有 name 和 age 字段。我试图通过比较名称以升序插入Friend 对象,但我的代码中处理两个匹配名称的部分遇到了问题。
我要么得到空指针异常,要么打印的列表有问题。
填充列表
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Travis", 19);
l.add("Kyler", 14);
l.add("Abby", 10);
l.add("Bob", 19);
l.add("Travis", 12);
l.add("Zander", 99);
l.printList();
}
LinkedList类:
public class LinkedList {
Friend head;
int listcount;
public LinkedList(){
head = null;
listcount = 0;
}
public void add(String name, int age){
Friend node = new Friend(name,age);
if(head==null){
head = node;
return;
}
if(head.name.compareTo(node.name) > 0){
node.nextName = head;
head = node;
return;
}
Friend current = head;
Friend previous = null;
while(current.name.compareTo(node.name) < 0 && current.nextName != null){
previous = current;
current = current.nextName;
}
if(current.name.compareTo(node.name) == 0 && current.age < node.age){
node.nextName = current.nextName;
current.nextName = node;
}
previous.nextName = node;
node.nextName = current;
}
public void printList(){
Friend temp = head;
while(temp!=null){
temp.print();
temp = temp.nextName;
}
}
}
Friend类:
public class Friend {
String name;
int age;
Friend nextName;
Friend nextAge;
public Friend(String name, int age){
this.name = name;
this.age = age;
nextName = null;
nextAge = null;
}
public void print(){
System.out.println(name+" "+age+". ");
}
}
【问题讨论】:
-
我认为第一个问题是
Friend不应该保持对下一个Friend的引用。您应该为此创建一个Node类并单独的职责。 -
我试图让
Friend充当Node类。将两者分开可以让我做什么? -
如果一个类同时负责许多事情,则称为code smell/antipattern(不良代码设计的标志)。你应该分开职责。
-
我认为
Node<T>(这里是Node<Friend>)是正确的方法。除此之外,我不知道如何建议修复错误......看起来你写了一个非常奇怪的链表...... -
为什么不在名字上使用
TreeMap和Comparator?
标签: java algorithm sorting data-structures linked-list