搞清楚递归的定义:
reverse:输入一个节点 head,将「以 head 为起点」的链表反转,并返回反转之后的头结点。
reverseN:输入一个节点 head,将「以 head 为起点」的前n个节点反转,并返回反转之后的头结点。
reverseBetween
class Solution {
public:
ListNode* successor = NULL;
ListNode* reverseN(ListNode* head, int n){
if(n==1){
successor = head->next;
return head;
}
ListNode* last = reverseN(head->next, n-1);
head->next->next = head;
head->next = successor;
return last;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left==1){
return reverseN(head,right);
}
head->next = reverseBetween(head->next, left-1, right-1);
return head;
}
};