各种错法:

  1. prev 初始化为ListNode(0)而不是null;
1
2
3
4
5
6
7
8
9
10
11
public ListNode reverseList(ListNode head) {
ListNode prev = new ListNode(0);

while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}

Submission : Wrong Answer

1
2
3
Input: [1,2,3,4,5]
Output: [5,4,3,2,1,0]
Expected: [5,4,3,2,1]

  1. prev 初始化带有自己的next:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public ListNode reverseList(ListNode head) {
    ListNode prev = new ListNode(0);
    prev.next = head;

    while (head != null) {
    ListNode next = head.next;
    head.next = prev;
    prev = head;
    head = next;
    }
    return prev;
    }

Submission : N/A

1
2
3
Input: [1,2,3,4,5]
Output: Found cycle in the ListNode
Expected: [5,4,3,2,1]

Correct:

1
2
3
4
5
6
7
8
9
10
11
public ListNode reverseList(ListNode head) {
ListNode prev = null;

while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}