2016-04-19 258 views
3

將節點添加到鏈接的末尾時遇到問題 代碼非常明顯,addToEnd方法將單個節點添加到鏈表的末尾。將節點添加到鏈表末尾

public class ll5 { 
    // Private inner class Node 

    private class Node{ 
     int data; 
     Node link; 

     public Node(int x, Node p){ 
      data = x; 
      link = p; 
     } 
    } 
    // End of Node class 

    public Node head; 

    public ll5(){ 
     head = null; 
    } 

    public void addToEnd(int data) { 
     Node p = head; 
     while (p.link != null) 
      p=p.link; 
     p.link=new Node(data, null); 
    } 


    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     ll5 list = new ll5(); 

     list.printList(); 
     System.out.println("How many values do you want to add to the list"); 
     int toAdd = input.nextInt(); 

     for(int i = 0; i < toAdd; i++) { 
      System.out.println("Enter value " + (i + 1)); 
      list.addToEnd(input.nextInt()); 
     } 

     System.out.println("The list is:"); 
     list.printList(); 

     input.close(); 
    } 

} 

爲什麼它給了我一個NullPointerException錯誤?該錯誤位於addToEnd方法的while循環中。

+0

我想,'節點p = head'使得'P = null'因爲'head'是'null'當你調用'addToEnd '第一次。 – StepTNT

回答

2

當列表沒有任何內容且head爲空時,您還沒有處理初始條件。因爲你得到NPE。

以下方法應該工作。

public void addToEnd(int data) { 
    Node p = head; 
    if(p == null) { 
     head = new Node(data, null); 
    } else { 
     while (p.link != null) 
      p=p.link; 
     p.link=new Node(data, null); 
    } 
} 
0

這是因爲頭是在一開始空

public ll5(){ 
    head = null; // <-- head is null 
} 

public void addToEnd(int data) { 
    Node p = head; //<-- you assigned head, which is null, to p 
    while (p.link != null) //<-- p is null, p.link causes NullException 
     p=p.link; 
    p.link=new Node(data, null); 
}