gpt4 book ai didi

java - 练习单链表实现,被我的列表反转方法抛出 NullPointerException 难住了

转载 作者:行者123 更新时间:2023-12-02 05:03:10 26 4
gpt4 key购买 nike

这是我的单链表代码:

public class SinglyLinkedList {

private static Node head;
private static int listSize;

private static class Node {

int value;
Node next;

Node(int i) {
value = i;
next = null;
}
}

public static void main(String[] args) {
head = null;
listSize = 0;
for (int i = 0; i < 10; i++) {
Node n = new Node(i);
if (head == null) {
head = n;
} else {
getLastNode(head).next = n;
}
listSize++;
}
printNodeValues(head);
Node revHead = reverseList(head);
printNodeValues(revHead);
}

private static Node reverseList(Node head) {
Node reverseHead = getLastNode(head);
Node reference = reverseHead;
while (listSize>0){
Node temp = getPreviousNode(reference, head);
Node last = getLastNode(reverseHead);
temp.next = null;
last.next = temp;
reference = temp;
listSize--;
}
return reverseHead;
}

private static Node getPreviousNode(Node reference, Node head) {
Node temp = head;
while (temp != null) {
if (temp.next == reference) {
break;
} else {
temp = temp.next;
}
}
return temp;
}

private static Node getLastNode(Node n) {
Node temp = n;
while (temp != null) {
if (temp.next == null) {
break;
} else {
temp = temp.next;
}
}
return temp;
}

public static void printNodeValues(Node h) {
while (h != null) {
System.out.print(h.value + " ");
h = h.next;
}
System.out.println();
}
}

问题出在我的reverseList(Node)方法上。当我运行该程序时,出现以下错误:

Exception in thread "main" java.lang.NullPointerException
at SinglyLinkedList.reverseList(SinglyLinkedList.java:44) -> temp = null;
at SinglyLinkedList.main(SinglyLinkedList.java:33) -> Node revHead = reverseList(head);

我的 printNodeValues 工作正常,并且可以打印

0 1 2 3 4 5 6 7 8 9

我正在尝试使用reverseList来打印

9 8 7 6 5 4 3 2 1 0。

最佳答案

你的代码中有很多非常糟糕的东西。最糟糕的是:为什么一切都是静态的?编写只能实例化一次的列表类有什么意义?

然后,列表的大小永远不会受到反向操作的影响,并且您甚至不需要计数器,因为您只需迭代列表,直到找到没有后继的节点。

private static Node reverseList(Node head) {
Node res = null;
while (head != null) {
Node node = new Node(head.value);
node.next = res;
res = node;
head = head.next;
}
return res;
}

关于java - 练习单链表实现,被我的列表反转方法抛出 NullPointerException 难住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28058186/

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