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);
请解释。