I started studying the linked lists and saw a code snippet that looks like this:
public class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int d) {data = d;}
}
private void append(int newData) {
Node newNode = new Node(newData);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
newNode.next = null;
last.next = newNode;
}
}
My question is if the newNode.next = null;
line is really necessary or if it's just a good practice because in the Node newNode = new Node(newData);
line after allocating the node and putting the data, newNode.next
will be null
.
CodePudding user response:
Setting newnode.next = null
is not required, and you are correct that it should already be null after instantiation.