0
我試圖建立一個字典順序鏈接列表。我在紙上計劃了所有內容,並認爲我需要一切正確,但是一旦我插入第二個或第三個條目,它將返回一個空指針異常。Lexographically有序的鏈表返回空指針異常
Exception in thread "main" java.lang.NullPointerException
at DoublyLL.insert(DoublyLL.java:88)
如果我進入,爲例子:
"chris", "andy", then "bob", "bob" returns the excpetion.
"chris", "bob", then "andy", "andy" returns the exception
"andy", "bob", I get the same exception with the addition of at DoublyLL$Node.access$000(DoublyLL.java:148)
代碼:
public boolean insert(StudentListing newListing)
{ Node n = new Node();
if(n == null) // out of memory
return false;
else
{
Node q = new Node();
q = h;
int lex;
if (q.next == null) // first inputed node
{
n.next = q.next;
q.next = n;
n.back = q;
n.l = newListing.deepCopy();
return true;
} else // not first node
{
q = q.next;
do
{
// This is the line the error is called vvv
lex = q.l.getKey().compareTo(newListing.getKey());
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if (lex < 0)
{
// keep going
q = q.next;
} else if (lex > 0)
{
// place before q
n.back = q.back;
q.back = n;
n.next = q;
n.back.next = n;
return true;
} else if (lex == 0)
{
// q and listing match
}
} while (lex < 0);
}
}
return false;
}
Inner class
public class Node
{ private StudentListing l;
private Node next;
private Node back;
public Node()
{ }
}