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:
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.
AC代码:
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode before,start,p,q,pre,temp;
before=start=p=q=temp=null;
pre=head;
for( int i=1; i<m; i++ ){
before = pre;
pre = pre.next;
}
start = p = pre;
// q = pre.next;//尽量用现有的变量代替
//reverse list between m and n
for( int i=m; i<=n; i++ ){
temp = pre.next;
pre.next = p;
p = pre;
pre = temp;
}
if( before == null ){
head = p;
}else{
before.next = p;
}
start.next = temp;
return head;
}
}