我正在尝试实现Java链接列表。每当我尝试删除倒数第二个节点时,程序就会给我一个空指针。
以下是属性:
public class Nodo {
int num;
boolean used;
Nodo next;
}
到目前为止这是方法:
public int delete(int val) { // deletes, (1:deleted, 0:not found, -1:empty
// list)
int deleted = 0;
if (n.used) {
if (n.next == null) {
if (n.num == val) {
n.used = false;
deleted = 1;
}
} else {
Nodo it = n;
Nodo itAnt = null;
while (it.next != null) {
if (it.num == val) {
it.num = it.next.num;
it.next = it.next.next;
deleted = 1;
}
itAnt = it;
it = it.next;
}
if (it.num == val) {
itAnt.next = null;
deleted = 1;
}
}
} else {
deleted = -1;
System.out.println("Empty list");
}
return deleted;
}
我该如何解决这个问题?
答案 0 :(得分:1)
当然这段代码会引发异常。 这是场景:
it
有可能是列表中倒数第二个节点,it.num
将等于val
。
现在,在第一次迭代之后,此while循环将具有以下值:
while (it.next != null) {
if (it.num == val) {
it.num = it.next.num;
it.next = it.next.next;
// "it.next" will be null. because "it" was one to last in the list.
deleted = 1;
}
itAnt = it; // This is the last item in the list
it = it.next; // Here "it" will be null, because "it.next" is null
}
当第二次迭代时,it.next
将抛出NullPointerException,因为it
已经为空。
还值得一提的是,您不需要这一行:Nodo it = n;
因为它是一个对象引用,n
和it
都指向同一个对象。因此,无论您在it
上做什么,都会直接影响n
。