2012-03-10 11 views
0

私は辞書順に並べられたリンクリストを作成しようとしています。私は紙の上にそれをすべて計画し、私はすべての権利が必要だと思ったが、一度私は2番目または3番目のエントリを挿入すると、nullポインタの例外を返します。Lexographically ordered linked listはnullポインタ例外を返します

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() 
{ } 
} 

答えて

1

最大の問題は、ここにあなたがいるときに、ということです新しいを挿入するを空でないリストに追加する場合は、挿入するStudentListingより大きい要素が見つかるまでリストを反復処理します。しかし、挿入しようとしているStudentListingがリストのどの要素よりも大きい場合、そのような要素は決して見つからないので、リストの最後を実行します。 q = q.nextを書き込む前に、q.next == nullがあるかどうかをチェックし、そのケースを適切に処理する必要があります。 Javaは例外を発生させることではなく、null —が、どれを返すことによって、メモリ不足エラーを示すため

(あなたのコード内のさまざまな小さな非Java-ISMSは、—は、例えば、if(n == null) // out of memoryは真ではありませんもあります私の大きな問題のように見えます)