删除单链接列表的第一个节点时NullpoInterException
我正在尝试制作一种方法,该方法可以删除大于输入最大值的链接列表中的任何值。我已经写出了代码,它适用于每种情况,除非第一个节点大于输入最大值,否则输入最大值会产生NullPoInterException。我希望有人可以帮助我。
这是我到目前为止的代码:
public static void removeValuesLargerThanMax(SinglyLinkedList list, int max){
Node cur = list.head;
Node prev = null;
while(cur != null){
if(cur.data > max){
prev.next = cur.next;
cur = cur.next;
continue;
}
prev = cur;
cur = cur.next;
}
}
I am trying to make a method that removes any value in a linked list that is larger than the input max. I have written out the code and it works for every case except when the first node is greater than the input max value, which then produces a NullPointerException. I was hoping that someone could help me out.
Here is the code I have so far:
public static void removeValuesLargerThanMax(SinglyLinkedList list, int max){
Node cur = list.head;
Node prev = null;
while(cur != null){
if(cur.data > max){
prev.next = cur.next;
cur = cur.next;
continue;
}
prev = cur;
cur = cur.next;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这条线中
prev.next = cur.next;
当第一个节点大于最大输入时,prev值为null。这就是为什么您会遇到错误。
In this line
prev.next = cur.next;
when first node is greater than max input then prev value is null. That's why you're getting the error.
当您穿越链接列表时,您正在跟踪
prev
,我假设在您穿越它时,我假设链接列表中的先前元素。但是,请记住,(非圆形)链接列表的第一个元素 没有以前的元素。在这种情况下,当您试图删除链接列表的第一个元素时,以下代码执行:
但是,
prev
的值以来没有更改,因为它被初始化为null 。然后,这将导致
nullpoInterException
。只需在尝试更新之前,先检查
prev
是null
。您可以做这样的事情(也更新头指针):As you traverse the linked list, you are keeping track of
prev
, I'm assuming as the previous element in the linked list as you traverse it. However, remember that the first element of a (non-circular) linked list does not have a previous element.In this case, when you are trying to remove the first element of the linked list, the following code executes:
However, the value of
prev
has not changed since it was initialized tonull
. Then, this would cause aNullPointerException
.Simply check if
prev
isnull
before attempting to update it. You could do something like this (also updating the head pointer):