Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked list removing from head [closed]

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?

like image 395
sam_rox Avatar asked Dec 11 '25 15:12

sam_rox


1 Answers

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;
} 
like image 172
T.G Avatar answered Dec 14 '25 04:12

T.G