主要思路 把链表分为三个部分 左中右

中间部分链表反转 形成新的中间部分

再拼接新的中间部分


/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param m int整型 
     * @param n int整型 
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        if(head == null){
            return head;
        }
        ListNode lefthead = new ListNode(-1);
        lefthead.next = head;
        ListNode curr = lefthead;
        ListNode   midNode = null;
        int i = 1;
        while(curr != null){
            if(i == m){
                midNode = curr.next;
                curr.next = null;
                break;
            }
            curr = curr.next;
            i++;
        }
        
        ListNode ptr = midNode;
        ListNode rightNode = null;

        int j = 1;
        while(ptr != null){
            if(j==n-m+1){
                rightNode = ptr.next;
                ptr.next = null;
            }
            ptr = ptr.next;
            j++;
        }
        ListNode reversedMidNode = reverseListNode(midNode);
        ListNode p = lefthead;
        while(p.next != null){
            p = p.next;
        }
        p.next = reversedMidNode;
        while(p.next != null){
            p = p.next;
        }
        p.next = rightNode;
            return lefthead.next;
    }
    
    public ListNode reverseListNode(ListNode head){
          if(head == null){
              return head;
          }
        ListNode prev = null;
        ListNode curr  = head;
        while(curr != null){
            ListNode nextNode = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextNode;
        }
        return prev;
    }
}