1

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

2 Answers2

1

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.

MattPutnam
  • 2,927
  • 2
  • 17
  • 23
0

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();
Steven Hansen
  • 3,189
  • 2
  • 16
  • 12
  • Are you free to skype for a few minutes? I'm experiencing a really weird bug when debugging and I don't even know how to describe it without sharing my screen. – user2738003 Feb 11 '14 at 23:55