递归初识

递归初识

特点 将复杂问题分解后,各个子问题的处理方法有相似性和继承性

处理时不可过于纠结递归的过程,否则会把自己陷进去

一定到明确自己所写递归函数的含义

每一层递归都要把问题缩小,(指的是问题规模,复杂度,如反转链表时,不断将自己所处理的链表缩小),直至base case,直接解决.

leetcode 剑指offer 24

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    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

/**
 * 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* reverseBetween(ListNode* head, int left, int right) {
        if(head==NULL){
            return head;
        }
        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 n){
         
         if(head==NULL){
             return head;
         }
        if(n==1){
           successor=head->next;
            return head;
        }
        ListNode* last= reverseN(head->next,n-1);
        head->next->next=head;
        head->next=successor;
        return last;
    }
};
posted @ 2021-06-08 08:37  niu_a  阅读(19)  评论(0编辑  收藏  举报