题解 | #链表内指定区间反转# 反转一下
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*;
public class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
if(head == null || head.next == null) return head;
ListNode ret = head;
ListNode pre = null,next = null;
for(int i=1; i<m; i++){
pre = head;
next = head.next;
head = head.next;
}
ListNode tempHead = head, tempPre = pre;
boolean flag = false;
for(int j=m-1; j<n; j++) {
next = head.next;
head.next = pre;
pre = head;
head = next;
flag = true;
}
if(tempPre != null) {
tempPre.next = pre;
}
if(flag) {
tempHead.next = next;
}
if(m > 1) {
return ret;
}
return pre;
}
}

