反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode du = new ListNode(-1); du.next = head; ListNode sl = head,fa = head; ListNode pre = du; for(int i = 0;i < n - m;i++){ fa = fa.next; } for(int i = 0;i < m - 1;i++){ pre = sl; sl = sl.next; fa = fa.next; } ListNode left = fa.next; fa.next = null; pre.next = left; //反转 pre为哑结点 while(sl != null){ ListNode tem = sl.next; //注意此步 sl.next = pre.next; pre.next = sl; sl = tem; } return du.next; } }