using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ 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 if(m==1) return reverseToN(head, n, out ListNode next); head.next=reverseBetween(head.next, m-1, n-1); return head; } public ListNode reverseToN(ListNode head,int N,out ListNode nextNode) { if(N==1) { nextNode=head.next; return head; } ListNode last=reverseToN(head.next, N-1,out nextNode); head.next.next=head; head.next=nextNode; return last; } }
关键在于利用翻转前N个函数,如果不是从head开始反转,那就直接往下迭代即可!