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