java - 将 null 分配给链表中的对象会出错

标签 java sorting doubly-linked-list

当我执行这一行时,我得到一个 NullPointerException:

temp.previous.next = null;

在下面代码的最后一个 else 中。

Contact 类是链表的一个节点。

谁能看出问题出在哪里?

public Contact delete(){
    Scanner keyboard  =new Scanner(System.in);
    Contact temp = first;
    System.out.print("Enter a name: ");
    String name = keyboard.next();
    while (temp != null) {
        if (temp.name.equalsIgnoreCase(name)) {
            break;
        }
        temp = temp.next;
    }
    if (temp == null) {
        System.out.println("record not found.");
    } else if (count == 1) {
        first = null;
        last = null;
        count--;
        return temp;
    } else if (count==2) {
        if (temp == first) {
            temp.next.previous = null;
            first = temp;
            count--;
            return temp;
        } else {
            first.next = null;
            count--;
            return temp;
        }
    } else if (count >= 3) {
        if (temp == first) {
            temp.next.previous = null;
            first = temp.next;
            count--;
            return temp;
        } else {
            if (temp.next != null) {
                temp.next.previous =temp.previous;
                temp.previous.next = temp.next;
                count--;
                return temp;
            } else {
                temp.previous.next = null; // <-- NPE here!
                count--;
                return temp;
            }
        }
    }
    return temp;
}

最佳答案

您正在将 null 分配给 temp.previous.next,但您没有检查 temp.previous 是否不为 null。

此外,您使用 first 初始化 temp,它可能(作为“first”)没有前一个节点 - 即 temp.previous 会可能为空。

因此,您很可能在尝试执行问题代码时遇到 NullPointerException

QED。

关于java - 将 null 分配给链表中的对象会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712087/

相关文章:

java - 为什么 listFiles() 在不同平台上表现不同?

c - 如何保存指向最后一个节点的指针

java - 如何在 java 中使用泛型类型的节点创建 get 方法

java - 如何在Java中引用列表中的内部类

java - 暂停后继续倒计时

java - 在 javax 库中使用 Float 字段时如何使用 @Size 验证?

javascript - 我的 .sort() 仅对输入框中添加的值进行排序?为什么是这样

xml - 如何使用 XSLT 获取信息并对仅具有标识符的元素子集进行排序?

excel - 计算列中的唯一数据,然后将其与另一个唯一数据匹配

Java变量/对象?双向链表逻辑