各种错法:
prev
初始化为ListNode(0)
而不是null
;
1 | public ListNode reverseList(ListNode head) { |
Submission : Wrong Answer
1
2
3Input: [1,2,3,4,5]
Output: [5,4,3,2,1,0]
Expected: [5,4,3,2,1]
prev
初始化带有自己的next
:1
2
3
4
5
6
7
8
9
10
11
12public 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
3Input: [1,2,3,4,5]
Output: Found cycle in the ListNode
Expected: [5,4,3,2,1]
Correct:
1 | public ListNode reverseList(ListNode head) { |