关于反向链表的问题(leetcode 206)



我知道我的代码完全错了,但我不知道我做错了什么,

有人能指出并解释我做错了什么吗?

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;
}

更改:

  1. head.next=null;//使列表的末尾为空

  2. current.next=prev;//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;
    }
    

替代解决方案

我们可以说while head != null,然后使用prev节点将其反转,最后我们将返回prev。这会更容易:

public final class Solution {
public static final ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode nextNode;
while (head != null) {
nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
}

最新更新