java - "NullPointerException"对双链表进行排序时

标签 java list nullpointerexception

我正在研究指针的概念。下面的列表有假设的指针,一个指向前一个数字,另一个指向下一个数字。并且,还有一个指向当前数字的元素。当我运行代码时,控制台返回“NullPointerException”。代码背后的逻辑对我来说似乎没问题。我是初学者,非常感谢一些帮助。我尝试尽可能多地注释代码,以便更清楚地理解。谢谢。

aux = start; //aux points to the start of the list. both of them are of the type 'List'
            int prev = start.num; //prev points to the number on the start position. both of them are of the type 'int'
            while (aux.next != null) { //aux.next means the pointer to the next element in the list
                if (aux.num >= aux.next.num) { //if the current number is greater than the next number, or equal
                    prev = aux.next.num; //prev recieves the lower number
                    aux.next.num = aux.num; //the greater number is put after the lower number
                    aux.num = prev; //the lower number is put before the greater number
                }
                aux = aux.next; //the current element takes a step to the next element so I can progress through the list
                aux.num = aux.next.num;
        }

编辑:我忘了说这个列表必须按升序排列。它还必须按照另一个方法的降序排列。

最佳答案

它发生在 while 循环的最后两行。

aux = aux.next; //the current element takes a step to the next element so I can progress through the list
aux.num = aux.next.num;

在这里您分配aux = aux.next,然后您执行aux.num = aux.next.num;。 如果 aux 现在是列表的最后一个元素,则 aux.nextnullaux.next.num将抛出 NPE。

为了防止这种情况,您可以在访问 num 之前进行另一次检查:

aux = aux.next;
if(aux.next != null) {
    aux.num = aux.next.num;
}
else {
    break;
}

关于java - "NullPointerException"对双链表进行排序时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25788937/

相关文章:

android - 在 for 循环中动态创建按钮以在 ScrollView 中使用

java - 如何避免为每个 View 添加注入(inject)方法?

python - 将列表中的元素除以 2 的幂并维护列表

android - Android Fragment 中的按钮出现 NullPointerException onClick

java - 如何连接 JavaFX 中的可观察列表?

Python 列表和生成

java - JOGL 2.0 的 GLProfile 中的空指针异常

java - Opengl - 旋转、缩放、平移

java - 在 Ubuntu 9.10 中安装 Play Framework

java - 如何在 commons-lang 中使用 ToStringBuilder 设置 toString 方法的格式?