In this linked list method I try to add a item in sorted order, but I am getting a null pointer exception

…衆ロ難τιáo~ 提交于 2019-12-13 08:29:40

问题


    public void addNode(Car newCarEntry){
    ListNode currentNode;
    ListNode previousNode;
    ListNode newNode = new ListNode(newCarEntry);

    if (head == null || newCarEntry.isNewerThan(head.carItem)){
        newNode.next = head;
        head = newNode;
    }else{
        currentNode = head.next;
        previousNode = head;
        while(currentNode != null &&      !newCarEntry.isNewerThan(currentNode.carItem)){
            currentNode = currentNode.next;
            previousNode = currentNode;
        }
        newNode.next = currentNode;
        newNode = previousNode.next;
    }
}

回答1:


You have a mistake in the way you advance the pointers. Change:

        currentNode = currentNode.next;
        previousNode = currentNode;

to

        previousNode = currentNode;
        currentNode = currentNode.next;

Your way you make both currentNode and previousNode holding references to the same object, which is not what you want.

EDIT: Also your last line should be

    previousNode.next =  newNode;

insead

    newNode = previousNode.next;

because you are not attaching the new node to the list this way.



来源:https://stackoverflow.com/questions/6558511/in-this-linked-list-method-i-try-to-add-a-item-in-sorted-order-but-i-am-getting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!