-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseList2.java
More file actions
34 lines (34 loc) · 799 Bytes
/
Copy pathReverseList2.java
File metadata and controls
34 lines (34 loc) · 799 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;
* next = null;
* }
* }
*/
public class ReverseList {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode nil = new ListNode(Integer.MAX_VALUE);
nil.next = head;
ListNode tmp = nil;
int cnt = 0;
while(++cnt < m){
tmp = tmp.next;
}
ListNode left = tmp;
tmp = tmp.next;
ListNode last = null;
while(cnt++ <= n){
ListNode nx= tmp.next;
tmp.next = last;
last = tmp;
tmp = nx;
}
left.next.next = tmp;
left.next = last;
return nil.next;
}
}