2012-03-06 56 views
0

我得到這個異常,這似乎是我正在做一個節點是空的東西。有人可以解釋我是如何做到這一點的?什麼是構造函數應該看起來像?我已經看到了空或有頭和尾虛擬節點..雙鏈表 - 空指針異常再次

//default constructor 
public AddressList() { 

} 

    //get size 
public int size() { 
    return counter; 
} 

public void addEntryNode(){ 
    //create the new node 
    EntryNode n = new EntryNode(); 
    //set the data 
    System.out.println("Enter first name: "); 
    n.myFirstName = keyboard.next(); 
    n.setFirstName(n.myFirstName); 

    System.out.println("Enter Last Name: "); 
    n.myLastName = keyboard.next(); 
    n.setLastName(n.myLastName); 

    System.out.println("Enter Email Address: "); 
    n.myEmail = keyboard.next(); 
    n.setEmail(n.myEmail); 

    System.out.println("Enter Phone Number: "); 
    n.myPhoneNum = keyboard.next(); 
    n.setPhoneNum(n.myPhoneNum); 

    n.setIndex(index); 

    //add nodes to head of list 
    head.setPrev(n); 
    n.setNext(head); 
    head = n; 

    //up the count and index 
    counter++; 
+0

好像它是head.setPrev(N)。應該將它設置爲null嗎? – jackie 2012-03-06 01:09:48

+0

Ahhhh它應該是n.setPrev()XD – jackie 2012-03-06 01:10:12

回答

1

嗯,這似乎是最有可能的修復。將頭部初始化爲空,併爲列表爲空時添加條件。

public AddressList() { 
    head = null 
} 

而且你的條件應該是這樣的:

if (head == null) { // empty list 
    head = n 
} 
else { 
    head.setPrev(n); 
    n.setNext(head); 
    head = n; 
}