尝试将元素添加到循环链表时java.lang.NullPointerException

时间:2016-10-08 15:53:54

标签: java data-structures circular-list

我正在尝试将一个元素添加到循环链表中,但每当我尝试访问该节点时它都会抛出NullPointerException。这是我的代码: 编辑:我已经阅读了解释NullPointerExceptions的帖子,但没有任何效果。

public class CircularLinkedList<T> {
static private class Node<T> {
    public T data;
    public Node<T> next;

    Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }
}

private Node<T> first;

public void addFirst(T x){
    if (first.data.equals(null)){
        first.data = x;
        first.next = first;
    }else{
        Node<T> second = first;
        first.data = x;
        first.next = second;
    }
}

编辑:我已经用private Node<T> first = new Node(null, null);初始化了节点,不断抛出错误。还与first.data == null进行了比较,现在它终止了该过程。

编辑:这是完整的代码:

public class CircularLinkedList<T> {
    static private class Node<T> {
        public T data;
        public Node<T> next;

        Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    private Node<T> first = new Node(null, null);

    public void addFirst(T x){
        if (first.data == null){
            first.data = x;
            first.next = first;
        }else{
            Node<T> second = first;
            first = new Node(x, second);
        }
    }

    public void print() {
        while (first.data == null) {
            System.out.println(first.data);
            first = first.next;
        }
    }

    public static void main(String[] args) {
        CircularLinkedList<String> lst = new CircularLinkedList<String>();
        lst.addFirst("Z");
        lst.addFirst("A");
        lst.addFirst("B");
        lst.print();
    }
}

1 个答案:

答案 0 :(得分:2)

您在first.data.equals(null)语句中获得NPE,因为最初first变量本身为null。你必须像这样开始初始化它

private Node<T> first = new Node(null, null);

此外,您必须与null区别对比

if (first.data == null) {