-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseLinkedListII.java
65 lines (55 loc) · 1.32 KB
/
ReverseLinkedListII.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package linkedlist;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 08/18/2019
*
* 92. Reverse Linked List II
* https://leetcode.com/problems/reverse-linked-list-ii/
* Difficulty: Medium
*
* Approach: One Pass Recursion
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List II.
* Memory Usage: 34.6 MB, less than 100.00% of Java online submissions for Reverse Linked List II.
*
* @see LinkedListTest#testReverseLinkedListII()
*/
public class ReverseLinkedListII {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n) {
return head;
}
if (m == 1) {
return reverse(head, null, null, null, m, n);
}
reverse(head, null, null, null, m, n);
return head;
}
private ListNode reverse(ListNode curr, ListNode prev, ListNode start, ListNode end, int m, int n) {
if (curr == null) {
return prev;
}
ListNode next = curr.next;
if (m == 1) {
start = prev;
} else if (m < 1 && n > 1) {
if (m == 0) {
end = prev;
}
curr.next = prev;
} else if (n == 1) {
curr.next = prev;
if (end == null) {
prev.next = next;
} else {
end.next = next;
}
if (start == null) {
return curr;
}
start.next = curr;
return start;
}
return reverse(next, curr, start, end, --m, --n);
}
}