public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null) return head;
ListNode fake_head = new ListNode(0);
fake_head.next = head;
//move to the start point
ListNode pre = fake_head;
for(int i = 0; i < m  1; i ++){
pre = pre.next;
}
//do the reverse
ListNode cur = pre.next;
ListNode new_head = null;
for(int i = 0; i <= n  m; i ++){
ListNode next = cur.next;
cur.next = new_head;
new_head = cur;
cur = next;
}
//reconnect
pre.next.next = cur;
pre.next = new_head;
return fake_head.next;
}
Java solution with less pointers and detailed comments


In fact we don't need fake head
public ListNode reverseBetween(ListNode head, int m, int n) { ListNode current = head, pre = null, breakNode = null; int i = 0; while(++i<m){ // go to breakNode, which is node m1 breakNode = current; pre = current; current = current.next; } while(i++<=n){// Reverse nodes from m to n ListNode next = current.next; current.next = pre; pre = current; current = next; } if(breakNode==null) { // incase of m = 1, we connect head with node n+1 and return node n; head.next = current; return pre; } breakNode.next.next = current; // breakNode.next is the node m, we connect it with node n+1; breakNode.next = pre; // connect breakNode with node n; return head; }