空指针异常链接列表

时间:2015-01-31 18:48:37

标签: java pointers nullpointerexception

我正在为下面的代码得到一个NullPointerException,我不太明白为什么(或如何解决它)。我知道我的第一个节点(下一个)是null,并且我不能在没有引起空指针异常的情况下调用任何方法,但是如果不调用任何方法,我就不能使它'not null':(。在insert函数的第一个for循环中抛出空指针异常。

这是我的节点类:

public class Node {

public Node next;
public String word;

public Node(String word){
    this.word = word;
}

public void display(){
    System.out.println (word);
}

public String toString(){
    return word;
}

这是我的链表类

public class WordLinkedList {

private int size; //integer to store the size of the linked list (# of words)
private Node firstnode; // reference to first node

public WordLinkedList(){
    size = 0;
    firstnode = new Node(null); // setting first node to null - dummy node ... I think ???!!!
}

   public WordLinkedList(String[] arrayOfWords){
    for (int i = 0; i < arrayOfWords.length; i++){
        this.insert(arrayOfWords[i]);
    }
} 

public void insert(String newword){

   Node newNode = new Node(newword);

   for (Node iterator = firstnode.next; iterator != null; iterator =        newNode.next){
        if (iterator.word.compareTo(newword) < 0){
            if (iterator.next.word.compareTo(newword)>0){
                newNode.next = iterator.next;
                iterator.next = newNode;
            }
        }
        if (iterator.word.compareTo(newword) > 0){
            iterator.next = iterator;
            firstnode.next = newNode;
        }
    }
}

public void display(){
    Node theNode = firstnode;

    while (theNode != null){
        theNode.display();
        System.out.println("Next node: " + theNode.next);
        theNode = theNode.next;
        System.out.println();
    }
}

}

0 个答案:

没有答案