/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// 后驱节点
ListNode successor = null;
public ListNode reverseBetween(ListNode head, int m, int n) {
// base case
if (m == 1) {
return reverseN(head, n);
}
// 一直到反转的起点触发 base case
head.next = reverseBetween(head.next, m - 1, n - 1);
return head;
}
// 辅助函数,反转以 head 为起点的 n 个节点,返回新的头结点
public ListNode reverseN(ListNode head, int n) {
// base case
if (n == 1) {
// 第 n + 1 个节点
successor = head.next;
return head;
}
// 反转以 head.next 为起点的 n -1 个节点,返回新的头结点
ListNode last = reverseN(head.next, n - 1);
// 反转之后的尾节点和 head 节点连接起来
head.next.next = head;
// 反转之后的 head 节点和 n + 1 节点连接起来
head.next = successor;
return last;
}
}
leecode-92-反转链表 II
最新推荐文章于 2024-12-27 20:44:47 发布