Linked List NullPointerException Java - java

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();
}

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.

Related

Null Check when interating LinkedList throws NullPointerException

So I'm coding in Java, and I had to make a LinkedList manually. It is doubly linked, and the tail's next pointer points to null. I'm using this to iterate through the list until I reach the end for a sorting algorithm (bubble sort).
Node<?> current = a.getHead();
while (current.getNext() != null) { //this line throw a NullPointerException
//sorting algorithm
current = current.getNext();
}
Here's the code for getNext() as well:
Node<?> current = a.getHead();.
Why is Java throwing a NullPointerException here?
Problem is in line Node<?> current = a.getHead();
a.getHead(); is returning null.
Please check like -
while (current != null && current.getNext() != null) {
//sorting algorithm
current = current.getNext();
}

Why use "node.getNext( ) == null" as a convention for defunct node?

This is a code fragment from the book "Data Structures and Algorithms in Java (6th Ed.)" This is method is part of the LinkedPositionalList implementation.
I don't understand exactly what does the line:
"if (node.getNext( ) == null) // convention for defunct node"
is for. I'd appreciate some explanation about its functionality.
// private utilities
/** Validates the position and returns it as a node. */
private Node<E> validate(Position<E> p) throws IllegalArgumentException {
if (!(p instanceof Node)) throw new IllegalArgumentException("Invalid p");
Node<E> node = (Node<E>) p; // safe cast
if (node.getNext( ) == null) // convention for defunct node
throw new IllegalArgumentException("p is no longer in the list");
return node;
}
The implementation in the book you're asking about uses an explicit trailer node that represents a "one past the end" position in the structure. Therefore, all nodes in the list must have a next node. Therefore, if a node's getNext() method returns null that node isn't in the list.
In this case defunct node means a non existent node.
if (node.getNext( ) == null) // convention for defunct node
In this case, the node p has a method called getNext() which can return null, if it does, then it means its the last of the nodes. In other words there is no next node.
This kind of structures, as the name implies, link between each other. getNext() should return a position in memory where the next node is, if such position is not existent then, there is no node there.
Usually node will likely have a method called setNext(Position<E> next) this is the counterpart that saves the position of the next item for this node.
If you read in the book the "Doubly Linked list Implementation" part of chapter 7 explains the defunct position notion as a result of getting rid of any removed position (node) in the list. Because the remove() method implements that the position to be deleted is set to null value.
So the validate() method actually checks if the input position is not removed from the list.. how? once again, by checking if calling getNext() on it would get null value. If so, then it must have been set to null as a deleted position using the remove() method. Therefore it throws an error as the input position p is no longer in the list (since it's a deleted position).
To better understand, just refer to the delete() method there in the book. Here it is from the book:
// Removes the element stored at Position p and returns it (invalidating p).
public E remove(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
Node<E> predecessor = node.getPrev();
Node<E> successor = node.getNext();
predecessor.setNext(successor);
successor.setPrev(predecessor);
size−−;
E answer = node.getElement();
node.setElement(null); // help with garbage collection
node.setNext(null); // and convention for defunct node
node.setPrev(null);
return answer;
}

Why we can use Node head = null without instantiate the 'head' in Java?

I am reading someone's code. It is about getting input numbers and convert those number into a Linked list. The part of the code is like this:
class Node {
int value;
Node next;
Node() {
next = null;
}
}
Firstly We need to create a head node to indicate head and we let the head be null like this Node head = null.
My limited experiences of java tell me that head is supposed to be a Node type object here. So why we can use Node head = null without instantiate the head?
I think at least I should create Node head = new Node(); then we can use Node head = null;
Anyone can explain it to me?
Node head = null;
This line states that there are no items in the linked list. This is valid in Java and indicates that although head can contain a Node object (or an object of a derived class), it is currently empty.
To add an item to the list, there is likely some code such as:
public void addItemToLinkedList(int value) {
if (head == null) {
head = new Node();
head.value = value;
} else {
...
}
}
So if there is no first Node (when head equals null) then head is created. Otherwise if head already exists, the else block would execute which would look for the end of the list and add another Node.
head is supposed to be a Node type object here
This is optional. Java allows head to be a Node object, or null, to indicate that head is not referencing any nodes at all.
The value of null is special in Java. It is allowed to go wherever an object can go. It indicates that the variable to which you assign null is empty. This is perfectly fine, assuming that the rest of your program deals with null checking.

NullPointerException in a while loop using a Binary Tree node

I am using a binary tree structure here. I am getting a "NullPointerException" from the line containing the while statement. I am completely confused about why that would be.
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
// Move up the Binary Tree to create code.
while(currNode.getParent() != null) {
// The loop does some stuff that doesn't
// affect what is assigned to currNode.
// Move to the parent node for the next iteration.
currNode = currNode.getParent();
} // End the while loop.
return code; // Return the string of binary code.
Find value is a method from my BinaryTree class that searches for and finds the node containing specific data. I know this works from testing it separately outside of this implementation.
The only reason why the while-loop statement can throw a NPE is, when currNode is null. I suspect findValue() returned null.
I guess one fix (when you care about the topmost node) would be:
while(currentNode != null) {
rootNode = currentNode;
currentNode = currentNode.getParent();
}
Or the typical pattern which relies on boolean shortcut evaluation:
while(curentNode != null && currentNode.getParent() != null)
Or my prefered solution using guards:
if (currentNode == null)
throw NotFound(); // or return something
while(curentNode.getParent() != null) {
If you see the code:
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
I guess, currNode is getting some value if findValue() able to search data else it is returning NULL values.
When it returns a NULL value it will throw NPE.
To avoid it, you can modify your code a little bit.
while(currNode != null && currNode.getParent != null) {
// your code here
}

Setting myself to null - Java

I came across the following problem:
Delete a node in the middle of a singly linked list, given only access to that node. (head is not given)
Now there are a lot of solutions and they all do not work when the element to be deleted is the last node.
Why wouldn't this work?
public static void removeNode (Node n){
if(n.next == null){ //n is the last node
n= null;
return;
}
//handling general case here
}
Java passes parameters by value, so setting n to null has no effect outside of the method. This means the method essentially does nothing when passed the last node of a list.
You need to set null the reference in the previous node, not the variable that references to your last node, something like this:
if(n.next == null) {
prev.next = null;
return;
}
n is local to the method, so changing its value won't affect the list itself. You need to modify the next of the previous node, which you do not have access to.

Categories