插入双向链表(获取空指针异常)java

时间:2015-06-21 23:32:24

标签: java doubly-linked-list

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;

                }
            }       
    }

我只是想插入我的双向链表。我有另一种方法,调用插入与适当的参数添加到我没有在这里发布的链表,因为它是不必要的。第一次插入头部很好但是在第二次插入时,在调试我的程序时,我发现我在行temp.next = new Node(command, fileName, fileSize, temp, temp.next.next);上得到一个空指针异常 我无法看到我出错的地方有人可以帮忙吗?感谢

1 个答案:

答案 0 :(得分:0)

对于您插入的第一个元素,以空列表开头,以便它通过if块

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

所以head.next = null

当您插入第二个元素时,代码会跳转到else块

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

如果是第二项,

temp = head

temp.next = null

temp.next.next =>空引用异常(传递给构造函数的最后一个参数)

另外,查看代码,似乎不是将temp.next.next传递给要传递temp.next的构造函数。将该陈述改为

     temp.next = new Node(command, fileName, fileSize, temp, temp.next);
相关问题