例如:
返回 1→4→3→2→5→NULL.
示例1
输入:{1,2,3,4,5},2,4
返回值:{1,4,3,2,5}
输入:{1,2,3,4,5},2,4
返回值:{1,4,3,2,5}
输入:{5},1,1
返回值:{5}
1 import java.util.*; 2 3 /* 4 * public class ListNode { 5 * int val; 6 * ListNode next = null; 7 * } 8 */ 9 10 public class Solution { 11 /** 12 * 13 * @param head ListNode类 14 * @param m int整型 15 * @param n int整型 16 * @return ListNode类 17 */ 18 public ListNode reverseBetween (ListNode head, int m, int n) { 19 // write code here 20 // 先找到m 21 ListNode res = new ListNode(-1); 22 res.next = head; 23 24 ListNode pre = res; 25 ListNode cur = head; 26 27 for(int i=1;i<m;i++){ 28 pre = cur; 29 cur = cur.next; 30 } 31 32 // 从m反转到n 33 for(int i=m;i<n;i++){ 34 ListNode temp = cur.next; 35 cur.next = temp.next; 36 temp.next = pre.next; 37 pre.next = temp; 38 } 39 return res.next; 40 } 41 }