我构建了一个由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+". ");
}
}
答案 0 :(得分:1)
请像这样更改你的add()(我的意思是你的add()方法的最后一行);
if (current.name.compareTo(node.name) == 0 && current.age < node.age) {
node.nextName = current.nextName;
current.nextName = node;
} else if (current.name.compareTo(node.name) < 0 ) {
previous.nextName = current;
current.nextName = node;
} else {
previous.nextName = node;
node.nextName = current;
}
输出
Abby 10。 鲍勃19。 凯勒14。 特拉维斯12。 特拉维斯19。 赞德99。