2017.9.18
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/*
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
// write your code here
if( m >= n){
return head;
}
ListNode pre = new ListNode(-1);
// 指向第m个结点之前的那个结点
pre.next = head;
// 指向第m个结点
ListNode theM = head;
int tmpM = m;
while(pre != null && theM != null && m > 1){
pre = pre.next;
theM = theM.next;
m--;
}
if(m > 1){
return null;
}
while(theM.next != null && n > tmpM){
ListNode tmp = theM.next;
theM.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
n --;
}
if(n > tmpM){
return null;
}
if(tmpM == 0 || tmpM == 1){
return pre.next;
}
return head;
}
}