import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ 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 // 解题思路,首先把链表分成3段 // 第一段0-m-1 // 第二段m-n // 第三段n+1 ~ // 所以需要几个关键节点 // leftPre 区间左节点的前一个,left 区间左节点 // right 区间右节点,rightNext 区间右节点下一个 // 其中当m=1时,leftPre 就不存在了为了处理边界,所以在头部默认加一个节点 if(m == n){ return head; } ListNode root = new ListNode(-1); root.next = head; ListNode leftPre = root; ListNode left = null; ListNode rightNext = null; for(int i=1;i<=n;i++){ if(i == m-1){ leftPre = head; } if(i == m){ left = head; } if(i == n){ rightNext = head.next; } head = head.next; } ListNode pre = null; ListNode next = null; while(left != rightNext){ next = left.next; left.next = pre; pre = left; left = next; } leftPre.next.next = rightNext; leftPre.next = pre; return root.next; } }