我正在研究指针的概念。下面的列表有假设的指针,一个指向前一个数字,另一个指向下一个数字。并且,还有一个指向当前数字的元素。当我运行代码时,控制台返回“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.next
为 null
且 aux.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/