数据结构链表下一个错误。

时间:2014-05-06 09:27:10

标签: java data-structures

此代码:

package Datastructures;

public class ChainNode {

    Object element;
    ChainNode next;

    public ChainNode() {
    }

    public ChainNode(Object element) {
        this.element = element;
    }

    public ChainNode(Object element, ChainNode next) {

        this.element = element;
        this.next = next;
    }

    public static void main(String args[]) {
        ChainNode firstNode = new ChainNode("a");
        ChainNode newNode = new ChainNode("b", firstNode.next);
        ChainNode newNode2 = new ChainNode("c", firstNode.next.next);
        System.out.println(firstNode.element);
        System.out.println(newNode.element);
    }

}

堆栈追踪:

Exception in thread "main" java.lang.NullPointerException
    at Datastructures.ChainNode.main(ChainNode.java:24)

1 个答案:

答案 0 :(得分:0)

这是因为您构建了后续ChainNode个对象,并为前一个对象的null字段提供了next引用,而您应该引用之前的public static void main(String args[]) { ChainNode firstNode = new ChainNode("a"); ChainNode newNode = new ChainNode("b", firstNode); ChainNode newNode2 = new ChainNode("c", newNode); System.out.println(firstNode.element); System.out.println(newNode.element); } 字段对象本身。试试这个:

{{1}}