/** * 首先生成一个首节点 * t1指针保存m前一个节点 * t2指针保存n的后一个节点 * tail指针保存反转后的尾节点 * pre指针保存反转后的首节点 * t1.next = pre; * tail.next = t2; * * @param head * @param m * @param n * @return */ public static ListNode reverseBetween(ListNode head, int m, int n) { // write code here if (m == n) { return head; } int i = 0; int j = 0; ListNode node = new ListNode(0); node.next = head; ListNode cur = node; ListNode next; ListNode pre = null; ListNode t1 = node; ListNode t2 = null; ListNode tail = null; while (cur != null) { next = cur.next; if (i >= m && j <= n) { cur.next = pre; pre = cur; cur = next; } else if (i + 1 == m) { t1 = cur; } else if (j > n) { t2 = cur; break; } if (i < m) { i++; cur = next; tail = cur; } j++; } t1.next = pre; tail.next = t2; return node.next; }