给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-linked-list-ii
递归算法:
1. 定义 reverseTopNListNode(ListNode* head, int n) 函数,用于将前 n 个节点翻转
1) 在函数外定义变量 processor 空指针,只有当递归终止时,才将第 n + 1 个链表节点指 针赋给 processor,最后将翻转后的链表的尾部指向 processor
2. 递归调用 reverseBetween(ListNode* head, int left, int right) 函数,递归终止条件为 left == 1 ,此时题目退化为 求解某个链表的前 right - left + 1 个节点的翻转
c++
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- ListNode* processor = nullptr;
- ListNode* reverseTopNListNode(ListNode* head, int n) {
- if(n==1) {
- processor = head->next;
- return head;
- }
- ListNode* last = reverseTopNListNode(head->next,n-1);
-
- head->next->next = head;
- head->next=processor;
-
- return last;
- }
- ListNode* reverseBetween(ListNode* head, int left, int right) {
- if(left == 1) {
- return reverseTopNListNode(head,right-left+1);
- }
-
- ListNode* last = reverseBetween(head->next,left-1,right-1);;
- head->next = last;
- return head;
- }
- };