Day 11
题目:反转链表的一部分
leetcode链接:反转链表II
要点:递归
反转链表前N个节点
ListNode successor = null; // 后驱节点
// 反转以 head 为起点的 n 个节点,返回新的头结点
ListNode reverseN(ListNode head, int n) {
if (n == 1) {
// 记录第 n + 1 个节点
successor = head.next;
return head;
}
// 以 head.next 为起点,需要反转前 n - 1 个节点
ListNode last = reverseN(head.next, n - 1);
head.next.next = head;
// 让反转之后的 head 节点和后面的节点连起来
head.next = successor;
return last;
}
1、Java
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
if(left == 1){
// 相当于反转前right个节点
return reverseN(head, right);
}
// 前进到反转的起点触发base case
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
}
ListNode successor = null; // 后驱节点
// 反转以head为起点的n个节点,返回新的头节点
public ListNode reverseN(ListNode head, int n){
if(n == 1){
// 记录第n+1个节点
successor = head.next;
return head;
}
// 以head.next为起点,需要反转前n-1个节点
ListNode last = reverseN(head.next, n-1);
head.next.next = head;
// 让反转之后的head节点和后面的节点连起来
head.next = successor;
return last;
}
}
2、python
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if left == 1:
return Solution.reverseN(self, head, right)
head.next = Solution.reverseBetween(self, head.next, left - 1, right - 1)
return head
def reverseN(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
global successor
if n == 1:
successor = head.next
return head
last = Solution.reverseN(self, head.next, n - 1)
head.next.next = head
head.next = successor
return last