gpt4 book ai didi

尝试向循环链表添加元素时出现 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 03:18:33 25 4
gpt4 key购买 nike

我试图将一个元素添加到循环链表中,但每当我尝试访问该节点时,它都会抛出 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();
}
}

最佳答案

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

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

此外,您还必须以不同的方式与 null 进行比较

if (first.data == null) {

关于尝试向循环链表添加元素时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com