【发布时间】:2015-06-21 23:32:23
【问题描述】:
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); 上得到一个空指针异常
我看不到哪里出错了,谁能帮忙?谢谢
【问题讨论】:
-
我知道什么是空指针异常……但这并不意味着我总能解决它!
-
你看“如何解决”部分了吗?你的 for 循环说“temp 不是 null,所以 temp = temp.next (可以将 temp 设置为 null)。
-
第一次进入循环的 else 部分时,这不应该发生,因为 temp = head。但我的程序第一次执行 else 部分时出现错误。