双向链表 - 再次出现空指针异常

时间:2012-03-06 01:07:11

标签: java doubly-linked-list

我得到了这个异常,似乎是我正在处理一个null的节点。有人可以解释我是怎么做的吗?应该是什么样的构造函数?我已经看到它是空的或带有标题和拖车虚拟节点..

    //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++;

1 个答案:

答案 0 :(得分:1)

嗯,这似乎是最有可能解决的问题。将头初始化为null,并为列表为空时添加条件。

public AddressList() {
    head = null
}

你的情况会是这样的:

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