删除单链接列表的第一个节点时NullpoInterException

发布于 2025-02-04 11:07:26 字数 531 浏览 3 评论 0原文

我正在尝试制作一种方法,该方法可以删除大于输入最大值的链接列表中的任何值。我已经写出了代码,它适用于每种情况,除非第一个节点大于输入最大值,否则输入最大值会产生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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谜兔 2025-02-11 11:07:28

在这条线中
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.

久夏青 2025-02-11 11:07:28

当您穿越链接列表时,您正在跟踪prev,我假设在您穿越它时,我假设链接列表中的先前元素。但是,请记住,(非圆形)链接列表的第一个元素 没有以前的元素。

在这种情况下,当您试图删除链接列表的第一个元素时,以下代码执行:

prev.next = cur.next;
cur = cur.next;

但是,prev的值以来没有更改,因为它被初始化为null 。然后,这将导致nullpoInterException

只需在尝试更新之前,先检查prevnull。您可以做这样的事情(也更新头指针):

if(cur.data > max){
    if(prev != null) prev.next = cur.next;
    else list.head = cur.next;
    cur = cur.next;
    continue;
}

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:

prev.next = cur.next;
cur = cur.next;

However, the value of prev has not changed since it was initialized to null. Then, this would cause a NullPointerException.

Simply check if prev is null before attempting to update it. You could do something like this (also updating the head pointer):

if(cur.data > max){
    if(prev != null) prev.next = cur.next;
    else list.head = cur.next;
    cur = cur.next;
    continue;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文