2017-01-25 45 views
1

当我尝试使用InsertFront()方法添加对象时,出现NullPointerException。该DLIST代码:NullPointerException在双链表实现中

public class DList { 
protected DListNode head; 
    protected int size; 

protected DListNode newNode(Object item, DListNode prev, DListNode next) { 
    return new DListNode(item, prev, next); 
    } 

public DList() { 
    head=newNode(null,head,head); 
    size=0; 
    } 


public void insertFront(Object item) { 
    head.next.prev=newNode(item, head, head.next); 
    head.next=head.next.prev; 
    size++; 
} 

然而,这种错误不再当我改变DLIST构造函数,这表明了:

public DList() { 
     head=newNode(null,head,head); 
     head.prev=head; 
     head.next=head; 
     size=0; 
     } 

现在,我也明白,分配head.next & head.prev值解决了问题;但我不明白什么是需要seperately,说明这个时候我已经分配的“头”变量在构造函数中的第一行的prev和next节点:

head=newNode(null,head,head); 

请解释。

回答

1

在最初的构造,这可能不是做什么,你认为它是:

head=newNode(null,head,head); 

注意headnull开始,所以调用的是真的是这样的:

head=newNode(null,null /*prev*/, null /*next*/); 

insertFront您尝试引用head.next.prev,但由于head.nextnull你会得到一个例外。

另一种方式去思考你的老构造是将其分解成2行:

DListNode temp=newNode(null,head,head); // remember that head is null here 
head=temp; 

方法参数的赋值的变量之前评估。