首页 > 解决方案 > Insert a Node at the Tail of a Linked List in java

问题描述

I have my own linkedlist in eclipse and to insert a node at tail of linkedlist i have written a code -

void insertatlast( int data ) {
    Node insert = new Node( data );
    if( head == null) {
        head = insert;
        return;
    }

    Node temp = head;
    while(temp.next != null) {
        temp = temp.next;
    }
    temp.next = insert;
    insert.next = null;
}

I have tried to solve this question on Hackerrank but in it return type is not void so, I put:

return temp.next ; 

but it is showing runtime error:

Exception in thread "main" java.lang.NullPointerException
at Solution.insertNodeAtTail(Solution.java:61)
at Solution.main(Solution.java:84)

标签: javalinked-list

解决方案


在您共享的照片中,如果头部本身为空,则可能会出现空指针。您应该修改您的 while 条件以确保 temp!=null

while(temp!=null && ...)

推荐阅读