inserting into a doubly linked list (getting null pointer exception) java

304 views Asked by At
My code is as follows:

//Node class (inner class)
    private class Node
    {
        private String command;
        private String fileName;
        private int fileSize;
        private Node next;
        private Node prev;

        //constructor of Node
        private Node(String command, String fileName, int fileSize, Node prev, Node next)
        {
            this.command = command;
            this.fileName = fileName;
            this.fileSize = fileSize;
            this.prev = prev;
            this.next = next;
        }
    }

    private Node head;
    private Node tail;
    int size;

    //constructor of list
    public ReadInput()
    {
        diskSize = 0;
        head = null;
        tail = null;
        size = 0;
    }

    public void insert(String command, String fileName, int fileSize)
    {

          if (head == null)
            { 
                head = tail = new Node(command, fileName, fileSize, null, null );
                size ++;
            }

          else 
            {
                for(Node temp = head; temp != null; temp = temp.next)
                {

                        temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);
                        temp.next.next.prev = temp.next;
                        size++;
                        if ( fileName == temp.fileName)
                             System.out.println("ID already exists!");
                        break;

                }
            }       
    }

I'm just trying to insert into my doubly linked list. I have another method that calls on insert with the proper arguments to add to the linked list that i have not posted here since it's unnecessay. The first insertion into the head is fine but on the second insertion, while debugging my program, i find that i get a null pointer exception on the line temp.next = new Node(command, fileName, fileSize, temp, temp.next.next); I can't see where i'm going wrong can anyone help? thanks

1

There are 1 answers

2
KnightFox On BEST ANSWER

For the first element you insert, starts with an empty list so it goes through the if block

      head = tail = new Node(command, fileName, fileSize, null, null );

so head.next = null

when you insert the second element, code jumps to the else block

       temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);

in case of the second item,

temp = head

temp.next =null

temp.next.next => Null reference exception (last parameter passed to the constructor)

Also, looking at your code, it seems like instead of passing temp.next.next to the constructor you want to pass temp.next. change that statement to be

     temp.next = new Node(command, fileName, fileSize, temp, temp.next);