我一直在为我正在研究的自定义链表实验室研究这种添加方法。一旦插入新节点,我就无法弄清楚如何将值移动一个索引。这是我的源代码。
public void add(int index, Object element) throws IndexOutOfBoundsException {
if(index > size() || index < 0) {
throw new IndexOutOfBoundsException();
}
ListNode newNode = new ListNode(element, null);
if(head == null) {
head = newNode;
return;
}
ListNode nextNode = head.nextNode;
ListNode currNode = head;
int i = 0;
while(currNode!= null) {
if(index == i) {
break;
}
currNode = nextNode;
//Breaks down here with null pointer exception
nextNode = nextNode.nextNode;
}
currNode = newNode;
currNode.nextNode = nextNode;
}
最佳答案
当您迭代最后一个节点时,它会抛出空指针,下一个节点指向空。如果您必须在最后添加新节点,请检查下一个节点是否指向空。
此外,在您的代码中,您不会增加 i 的值,它总是会迭代整个列表。
关于java - 为自定义 LinkedList 类添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43174104/