Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.
对范围内的节点进行操作
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null) return head;
ListNode nhead = new ListNode(0);
nhead.next = head;
ListNode pre = nhead;
for(int i=0; i<m-1; i++) pre = pre.next;
ListNode start = pre.next;
ListNode end = start.next;
for(int i=0; i<n-m; i++){
start.next = end.next;
end.next = pre.next;
pre.next = end;
end = start.next;
}
return nhead.next;
}
}