我知道我的代码完全错误,但我不知道我哪里做错了,
谁能指出并解释我做错了什么?
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode current = head;
ListNode nextNode = head.next;
while (nextNode != null) {
prev = current;
current = nextNode;
current.next = prev;
nextNode = nextNode.next;
System.out.println(nextNode.val);
}
return current;
}
最佳答案
变化:
head.next = null;//使列表末尾为空
当前.下一个 = 上一个;//current 是对节点的引用,因此对其进行更改也会更改引用 nextNode 的节点
public ListNode reverseList(ListNode head) { if (head == null) { return head; } ListNode prev = null; ListNode current = head; ListNode nextNode = head.next; head.next = null; // to make the end of the list as null while (nextNode != null) { prev = current; current = nextNode; nextNode = nextNode.next; // first get next node, before ... current.next = prev; // ... overwriting it here // System.out.println(nextNode.val); } return current; }
关于algorithm - 关于反向链表的问题(leetcode 206),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63666299/