Reputation: 13
When trying to add things at a specific index to my linkedlist, I am receiving a nullpointerexception. I know why, but I don't know how to fix it.
Here is my code for the nodes of the linked list
public class LinkedList<Key> implements LinkedListInterface<Key>{
private Node head;
private Node tail;
private int size = 0;
private class Node{
Key key;
Node next;
}
And here is my code where I'm trying to add to the linked list at a specific index.
public void add(int index, Key key) {
if(index < size){
Node left = null, newNode = null;
Node right = head;
for(int i = 0; i < index; i++){
left = right;
right = right.next;
}
left.next = newNode;
newNode.next = right;
newNode.key = key;
size++;
}
else{
addToEnd(key);
}
}
private void addToEnd(Key key) {
Node lastNode = new Node();
if(size == 0){
tail = head = lastNode;
}
else{
lastNode.key = key;
tail.next = lastNode;
tail = lastNode;
}
size++;
}
I know that by default my nodes will be null, but I am unable to do anything with them until they have a value. However, it seems that in order to be able to assign a value to them, they can't be null. I just can't wrap my head around it.
Thanks for the help
Upvotes: 1
Views: 126
Reputation: 3017
It looks to me like you just need to initialize newNode
up there on the second line of add(...)
, rather than setting the variable to null.
Upvotes: 1
Reputation: 3211
When adding a node, you need memory allocated for the new node.
So, when you create newNode, allocate memory for it:
Node left = null, newNode = new Node();
Upvotes: 0