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

时间:2019-07-03 11:50:14

标签: java

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

1 2 3 4 5

您的输出是:

curr的数据为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后打印数据时,它会给出空点错误! ps。这是一个功能性问题

2 个答案:

答案 0 :(得分:0)

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对象,它也允许您向后浏览列表。

答案 1 :(得分:0)

分配当前值和下一个值的问题

Node reverseList(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; 
}