我一直在为我正在处理的自定义链接列表实验添加此方法。一旦插入新节点,我无法弄清楚如何将值移过一个索引。这是我的源代码。为自定义链接列表类添加方法
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;
}
LinkedList理想情况下不应该有任何索引号,这与数组不同。这就是LinkedList背后的概念。 –
@PritamBanerjee你能解释一下原因吗?我最近在cpp中建立了这个链表功能。谢谢 – Omore
链接列表只是串在一起的一堆节点。每个节点只知道下一个节点(单链表)。 – jmw5598