0
我構建了一個由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+". ");
}
}
我認爲一個第一問題在於,「朋友」不應該保留對下一個「朋友」的引用。你應該爲這個和*分開的職責*創建一個'Node'類。 –
我試圖讓'Friend'充當'Node'類。將兩者分開允許我做什麼? –
如果一個類同時負責許多事情,那麼它被認爲是[*代碼氣味/反模式*](https://en.wikipedia.org/wiki/Anti-pattern)(錯誤代碼設計的標誌)。你應該*分開責任*。 –