1

In LinkedList we normally assign null value to last node and also use this condition to check for the last node.

I am checking for the last node with the same condition either its "next" node link is null or not. But I'm unable to handle NullPointerException when I get null value by the method "getNext".

while(lastNode.getNext() != null)
{
lastNode= lastNode.getNext();
}
3
  • Are you sure this piece of code throwing a NullPointerException? Commented Nov 18, 2014 at 21:47
  • 1
    Can you paste the code for getNext()? Commented Nov 18, 2014 at 21:49
  • @elephont something like public Node<T> getNext() { return next; } - that's not what the issue is. Commented Nov 18, 2014 at 21:53

1 Answer 1

1

I assume this is a custom implementation of a LinkedList; java.util.LinkedList does not have a getNext() method.

That said, what you want is:

while (current != null) {
    past = current;
    current = current.getNext();
}

return past;

I am assuming here that you want to return the last node, and that past is a variable of the same type as current.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.