题目:
92. Reverse Linked List II(medium)
解题思路:
递归翻转链表的进阶版
将从位置m到n的翻转先转换成翻转前n个,看作m=1时的情形;
再递归扩展到m != 1的情形。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21java:
public ListNode reverseBetween(ListNode head, int m, int n) {
if(m==1)
return reverseN(head,n);
head.next = reverseBetween(head.next,m-1,n-1);
return head;
}
ListNode next = null;//后驱结点
private ListNode reverseN(ListNode head,int n){//反转链表前N个结点
if(n == 1){
//记住n+1个结点
next = head.next;
return head;
}
ListNode newHead = reverseN(head.next,n-1);
head.next.next = head;
head.next = next;
return newHead;
}