简体   繁体   English

为自定义LinkedList类添加方法

[英]Add method for custom LinkedList class

I have been working on this add method for a custom linkedlist lab I am working on. 我一直在为自己正在研究的自定义链表实验室研究这种添加方法。 I cannot figure out how to shift values over by one index, once I insert the new node. 插入新节点后,我无法弄清楚如何将值移动一个索引。 Here is my source code. 这是我的源代码。

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

It is throwing null pointer as when you are iterating last node, next node points to null. 当您迭代最后一个节点时,它将抛出空指针,下一个节点指向空。 Check for next node point to null also if you have to add new node in last. 如果必须在最后一个节点中添加新节点,请检查下一个节点是否为null。

Also in your code you are not increasing the value of i always it is iterating the whole list. 同样在您的代码中,您并没有增加i的价值,而是始终在遍历整个列表。

I don't really know what you are trying to achieve here, and I agree with @Pritam Banerjee's comment. 我真的不知道您要在这里实现什么,我同意@Pritam Banerjee的评论。 But an obvious problem in your code is that you are never incrementing i, so you'll never break out of your while loop and at some point you are going to hit the end of your list and nextNode.nextNode is going to be null, hence your exception. 但是代码中的一个明显问题是,您永远不会增加i,因此您永远也不会中断while循环,并且在某些时候您将到达列表的末尾,nextNode.nextNode将为null,因此,您例外。 (Also note that nextNode.nextNode will be null before currNode is.) (还请注意,在currNode之前,nextNode.nextNode将为null。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM