2016-06-09 26 views
0

我構建了一個由Friend對象組成的多鏈表。 Friend類有nameage字段。我試圖通過比較名稱來按升序插入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+". "); 
    } 
} 
+1

我認爲一個第一問題在於,「朋友」不應該保留對下一個「朋友」的引用。你應該爲這個和*分開的職責*創建一個'Node'類。 –

+0

我試圖讓'Friend'充當'Node'類。將兩者分開允許我做什麼? –

+1

如果一個類同時負責許多事情,那麼它被認爲是[*代碼氣味/反模式*](https://en.wikipedia.org/wiki/Anti-pattern)(錯誤代碼設計的標誌)。你應該*分開責任*。 –

回答

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; 
    } 

輸出

阿比10. 鮑勃19. Kyler 14. 特拉維斯12. 特拉維斯19. Zander的99.

+0

這與我在問題中使用的輸入一起工作,但如果只使用彼此相等的'name'字符串,則會拋出'空指針異常'。感謝您的幫助! –