英文:
addLast - doubly circular linkedlist - NullPointerException
问题
在双向循环链表末尾插入元素的方法是什么?为什么我运行这段代码时会出现“NullPointerException”?
public void addLast(String title, double length) {
if (isEmpty()) {
head = new Episode(title, length, head, head);
} else {
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);
}
}
英文:
How do you insert an item at the end of a doubly circular linked list? Why do I have a NullPointerException
when I run this?
public void addLast( String title, double length ){
if( isEmpty()){
head = new Episode(title, length, head, head);
}else{
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);
}
}
答案1
得分: 0
代码设置了新节点的引用,但没有更新列表中的现有引用。修正后的内容如下:
if (isEmpty()) { // 假设如果为空,head == null
head = new Episode(title, length, head, head);
head.next = head; // 修正
head.prev = head; // 修正
} else {
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);
last.next = new_episode; // 修正
head.prev = new_episode; // 修正
}
英文:
The code sets the new node's references, but doesn't update the existing references in the list. Fixed noted in commments:
if( isEmpty()){ // assuming if empty, head == null
head = new Episode(title, length, head, head);
head.next = head; // fix
head.prev = head; // fix
} else {
Episode last = head.prev;
Episode new_episode = new Episode(title, length, head, last);
last.next = new_episode; // fix
head.prev = new_episode; // fix
}
专注分享java语言的经验与见解,让所有开发者获益!
评论