import java.util.*; /* * 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) { if (m == n) { return head; } ListNode dummy = new ListNode(-1); dummy.next = head; ListNode prev = dummy; // 开始需要翻转的头结点 for (int i = 1; i < m; i++) { prev = prev.next; } // 要翻转的头结点 ListNode midHead = prev.next; // 右侧不动的头结点 ListNode tail = midHead; for (int i = m; i <= n; i++) { tail = tail.next; } // 翻转mid,这里把preTmp指向tail 主要是把他当做前节点,反转后,就在尾部了 ListNode preTmp = tail; ListNode cur = midHead; while (cur != tail) { ListNode next = cur.next; cur.next = preTmp; preTmp = cur; cur = next; } prev.next = preTmp; return dummy.next; } }