092.Reverse Linked List II

Solution 1: accepted 3ms 93%

Well, it shouldn’t be this long. Can we optimize it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
for (int i = 1; i < m; i++) {
head = head.next;
}
ListNode cur = head.next;
ListNode rev = null; // reversed part
ListNode tail = null;
int count = n - m;
for (int i = m; i <= n; i++) {
ListNode temp = cur.next;
if (rev != null) {
cur.next = rev;
rev = cur;
} else {
rev = cur;
tail = cur;
rev.next = null;
}
cur = temp;
count--;
if (i >= n) {
tail.next = cur;
head.next = rev;
}
}
return dummy.next;
}