gpt4 book ai didi

java - 链接列表在尝试访问其数据时出现空点错误

转载 作者:行者123 更新时间:2023-12-02 03:34:11 27 4
gpt4 key购买 nike

我需要反转我使用以下代码的链表的元素,但是我得到的输出为对于输入:5

1 2 3 4 5

您的输出是:

当前有数据 1

1预期输出:5 4 3 2 1

代码:

 Node reverseList(Node head)
{

Node curr=null;
Node node = head;
Node next=null;
while(node!=null){
next = curr;
curr = node;
System.out.println("curr has data " + node.data);
curr.next = next;

node = node.next;
//System.out,println(node.data)

}
return curr;

}

当我在将节点更改为node.next后尝试打印数据时,它给出了空点错误!附注这是一个功能问题

最佳答案

node 在一次迭代后实际上是 null

我评论了你的一些代码来解释:

Node reverseList(Node head) {
Node curr = null;
Node node = head;
Node next = null;
while (node) {
next = curr; // Here, curr is null, so next = null
curr = node;
System.out.println("curr has data " + node.data);
curr.next = next; // You are here doing 'curr.next = null' (see before)

node = node.next;
}
return curr;
}

这是来自 https://www.geeksforgeeks.org/reverse-a-linked-list/ 的解决方案反转链接列表:

Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}

顺便说一句,如果您还没有看过 ArrayList 对象,它也允许您向后浏览列表。

关于java - 链接列表在尝试访问其数据时出现空点错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56869475/

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