2017-04-02 53 views
0

我一直在为我正在处理的自定义链接列表实验添加此方法。一旦插入新节点,我无法弄清楚如何将值移过一个索引。这是我的源代码。为自定义链接列表类添加方法

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; 
} 
+1

LinkedList理想情况下不应该有任何索引号,这与数组不同。这就是LinkedList背后的概念。 –

+0

@PritamBanerjee你能解释一下原因吗?我最近在cpp中建立了这个链表功能。谢谢 – Omore

+1

链接列表只是串在一起的一堆节点。每个节点只知道下一个节点(单链表)。 – jmw5598

回答

2

它正在抛出空指针,因为当你迭代最后一个节点时,下一个节点指向空。如果必须在最后添加新节点,请检查下一个节点是否为空。

同样在你的代码中,你不会增加我总是迭代整个列表的价值。

0

我真的不知道你在这里想达到什么目的,我同意@Pritam Banerjee的评论。但是在你的代码中一个明显的问题是你永远不会增加我,所以你永远不会摆脱你的while循环,在某些时候你会打到你的列表的末尾,nextNode.nextNode将会是null,因此你的例外。 (另请注意,在currNode之前nextNode.nextNode将为空。)