NullPointerException при удалении головного узла [дубликат]JAVA

Программисты JAVA общаются здесь
Ответить
Гость
 NullPointerException при удалении головного узла [дубликат]

Сообщение Гость »

Код: Выделить всё

 public void remove(E del) { //this deletes head node
if (size == 0) {

}
else {
Node temp = head; //start at head
head = head.next; //head points to head.next
temp = head.next; //move to the next node after head
temp.prev = null; //set prev equal to null
head.next = null; //setting head's next equal to null to make empty

}
}

public String toString() {
Node temp = head; //temp node starting at head to walk the list

if (temp == null) return ""; //if there is nothing to start at return nothing

String output = "[ ";

for(int i = 0; i < size; i++) { //cycle through while i < size

if(i == 0) { //if is index 0, then grab the data of head
output += temp.data;
}
else { //else if i is more than 0, then grab the data of head and display with output
output += ", \n" + temp.data;
}
temp = temp.next; // sets the temporary head equal to temp.next;
}
output += " ]";
return output;
}
I am trying to create a

Код: Выделить всё

remove()
method that will remove the head node of the double linked list. I have tried many different ways to make this method work but every time I run the program, I am always method with

Код: Выделить всё

"NullPointerException: Cannot read field "data" because "temp" is null"
and I am not sure why I keep getting this error. When I read the error it always points back to line 191 which happens to be in the

Код: Выделить всё

toString()
method.
To remove the head node I figured that I would have to create a temp node that starts at the head node. After starting at the head node, I would use

Код: Выделить всё

head = head.next
to point to the next of head and then I would set that to

Код: Выделить всё

head.next = null
so it would severe the connection between the head and the node after it.


Источник: https://stackoverflow.com/questions/781 ... -head-node
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»