0
我試圖建立一個刪除功能,從列表中刪除一個特定的器官。 我收到NullPointerException的錯誤 我想知道我的錯誤是什麼。 爲什麼我得到這個錯誤。 謝謝。如何從通用雙向鏈表中刪除
A method to delete a specific organ. The method returns the deleted organ, organ lab is not on the list, it returns null
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class LinkedListDouble<T> {
private LDNode<T> head;
private LDNode<T> tail;
public int size;
LinkedListDouble(){
this.head = null;
size = 0;
}
public void add(T item){ // add item to the list
if(head == null){
head = new LDNode<T>(item,null,null);
}
else{
LDNode<T> n = new LDNode<T>(item, null, null);
while(n.next != null){
n = n.next;
}
n.next = new LDNode<T>(item,n,null);
}size++;
}
public T remove(T item){ // remove item from the list
T ans=null;
LDNode<T> n = head;
int i=0;
while(n.data != item){
n = n.next;
i++;
}
if(i == size) return null;
if(n == head) {
ans = head.data;
head.prev.next = head.next;
head.next.prev = head.prev;
head = head.next;
}
else {
ans = n.data;
n.prev.next = n.next;
n.next.prev = n.prev;
}
size--;
return ans;
}
public int size(){
return size;
}
節點:
public class LDNode<T> {
T data;
LDNode<T> next,prev;
LDNode(){
next = null;
prev = null;
data = null;
}
/*LDNode(T data){
this(data,null,null);
}*/
LDNode(T data , LDNode<T> next , LDNode<T> prev){
this.data = data;
this.next = next;
this.prev = prev;
}
LDNode(LDNode<T> Other){
this.data = Other.data;
this.next = Other.next;
this.prev = Other.prev;
}
T getData(){
return data;
}
public void setNextNode(LDNode<T> next){
this.next = next;
}
public LDNode<T> getPrevNode(){
return prev;
}
public void setPrevNode(LDNode<T> prev){
this.prev = prev;
}
public void setData(T data){
this.data = data;
}
public LDNode<T> getNextNode(){
return next;
}
}
主:
public static void main(String[] args) {
LinkedListDouble<Integer> itay = new LinkedListDouble<>();
itay.add(1);
itay.add(2);
itay.add(3);
itay.add(4);
itay.add(5);
itay.add(6);
System.out.println(itay.size());
itay.remove(1);
System.out.println(itay.size());
}
錯誤:
Exception in thread "main" java.lang.NullPointerException
at Matala2.LinkedListDouble.remove(LinkedListDouble.java:45)//head.prev.next = head.next;
at Matala2.LinkedListDouble.main(LinkedListDouble.java:78) //itay.remove(1);
「head」是'null'或'head.prev'。 '頭'不可能,或者你會得到一個例外的例外。所以'head.prev'爲null,所以你試圖分配給'head.prev.next'給NPE。 –
你有什麼期望'head.prev'應該提到?如果不研究代碼中的每一行,我都會認爲它是空的。 –
可能的重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –