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

标签 java

我需要反转我使用以下代码的链表的元素,但是我得到的输出为 对于输入: 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/

相关文章:

java - 您可以在二维数组上创建 Java 迭代器吗?

java - Eclipse插件: Custom plugin. xml类编辑器

java - RandomInt 和 If Else 问题

java - Spring + GWT 项目 - 对每个用户操作执行处理程序

java - 收集集合中对象的属性

java - 在 Mac 10.9 Mavericks 上从 Android 源构建 aapt 出现段错误,或者在 10.8 Mountain Lion 上给出 "Illegal Instruction 4"

java - 如何使用hibernate将结果集从mysql映射到pojo?

java - 如何在 spring 数据 elasticsearch 中将结果大小设置为零

java - HAX 正在运行并且模拟器在快速 virt 模式模拟器中运行。创建模拟器窗口不在 View 中并且重新居中

Java - 如何访问在 void 函数中创建的数组