2016-05-01 37 views
0

我想實現數據結構鏈表(單)然而通過添加元素返回NULLPOINTEREXCEPTION。LinkedList(custom)add()return NullPointerException

import java.util.NoSuchElementException; 

public class Linkedlist<ANYTYPE>{ 

private Node head; 

Linkedlist(){ 
    head = null; 
} 

public void add(ANYTYPE data){ 
    head.next = new Node<>(data, head); 
} 

public void traverse(){ 
    if(head == null) throw new NoSuchElementException("List may be empty"); 

    Node temp = head; 

    while(temp != null){ 
     System.out.println(temp.data+" "); 
     temp = temp.next; 
    } 
} 

public static void main(String[] args) { 

    Linkedlist<String> l=new Linkedlist<String>(); 
    l.add("one"); 
    l.add("two"); 
    l.traverse(); 
} 


private class Node<ANYTYPE>{ 

    private ANYTYPE data; 
    private Node next; 

    Node(ANYTYPE data, Node next){ 
     this.data = data; 
     this.next = next; 
    } 
} 

} 
+0

添加適當的標籤以獲得正確的答案,並嘗試在發佈前格式化您的代碼。 – Rahul

+0

問自己當列表爲空時,「head」的值是多少? –

回答

0

在添加( )方法,你必須檢查是否還有節點(正如你在traverse()方法中所做的那樣)。 if(head == null),則無法訪問.next成員。相反,您的第一個要添加的元素應該分配給頭部。

+0

謝謝拉胡爾,弗洛裏安我添加空檢查,如果每個方法頭是空的。 \t公共無效添加(ANYTYPE數據){ \t \t如果(頭== NULL) \t \t頭=新節點(數據,NULL); \t \t head = new Node <>(data,head); \t} –

0

呀原因在構造函數中要設置headnull所看到如下

Linkedlist(){ 
    head = null; 
} 

然後在Add()嘗試做head.next等異常

public void add(ANYTYPE data){ 
    head.next = new Node<>(data, head); 
}