-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (29 loc) · 838 Bytes
/
Solution.java
File metadata and controls
34 lines (29 loc) · 838 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == n) return head;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
for (int i = 0; i < m - 1; i++) pre = pre.next;
ListNode reverse = null,
cur = pre.next;
for (int i = 0; i < n - m + 1; i++) {
ListNode next = cur.next;
cur.next = reverse;
reverse = cur;
cur = next;
}
// the tail of reverse
pre.next.next = cur;
pre.next = reverse;
return dummy.next;
}
}