-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
44 lines (42 loc) · 987 Bytes
/
Copy pathSolution.java
File metadata and controls
44 lines (42 loc) · 987 Bytes
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
public class Solution
{
public ListNode reverseBetween(ListNode head, int m, int n)
{
if (head == null || m == n)
{
return head;
}
int i = 1;
ListNode prev = null;
ListNode start = head;
ListNode end = head;
while (i < n)
{
prev = i < m ? start : prev;
start = i < m ? start.next : start;
end = end.next;
i++;
}
ListNode tail = end.next;
end.next = null;
reverse(start);
if (prev != null)
{
prev.next = end;
}
start.next = tail;
return m > 1 ? head : end;
}
private ListNode reverse(ListNode node)
{
if (node == null || node.next == null)
{
return node;
}
ListNode nxt = node.next;
node.next = null;
ListNode reverse = reverse(nxt);
nxt.next = node;
return reverse;
}
}