递归魔法
LeetCode 206 反转链表 2023.12.26
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return last;
}
LeetCode 92 反转链表-ii 2023.12.26
class Solution {
public:
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;
}
ListNode* successor = NULL;
ListNode* reverseN(ListNode* head, int right)
{
if(right == 1)
{
successor = head->next;
return head;
}
ListNode* last = reverseN(head->next, right-1);
head->next->next = head;
head->next = successor;
return last;
}
};