在此链表方法中,我尝试按排序顺序添加项目,但出现空指针异常 [英] In this linked list method I try to add a item in sorted order, but I am getting a null pointer exception

查看:105
本文介绍了在此链表方法中,我尝试按排序顺序添加项目,但出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

前进指针的方式有误. 更改:

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

        currentNode = currentNode.next;
        previousNode = currentNode;

        previousNode = currentNode;
        currentNode = currentNode.next;

您使currentNode和previousNode都持有对同一对象的引用的方式,这不是您想要的.

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

另外,您的最后一行应该是

Also your last line should be

    previousNode.next =  newNode;

入海

    newNode = previousNode.next;

因为您不是以这种方式将新节点附加到列表中.

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

这篇关于在此链表方法中,我尝试按排序顺序添加项目,但出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆