In a linked list when there's only one Node situation and I try to remove it using reoveFromHead(); I get a nullpointer at the toString() method.
public void removeFromHead(){
if(head==null)
return;
else{
head=head.next;
}
}
public String toString() {
String result = " ";
ListNode a=head;
while (a.next!=null){
result +=" "+a.item;
a=a.next;
}
result+=" "+a.item;
return result;
}
Can someone please point out where the mistake is?
if head=head.next; gives you null (because there is no more items) then you cant call a.next because a is null.
public String toString() {
String result = " ";
ListNode a=head;
if(a!=null){
while (a.next!=null){
result +=" "+a.item;
a=a.next;
}
result+=" "+a.item;
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With