当前位置:网站首页>Understanding recursion

Understanding recursion

2022-06-12 13:34:00 You stole my name

The meaning of recursion

The Chinese understanding of recursion is transfer and regression , Passing means passing something between each level of recursion , Regression is to go back to the first recursion . Remember that a little recursive process is doing the same thing over and over again .

How to write recursion ?

A common template for recursion is :① The termination condition of recursion , That is, when the recursion ends ;② What this round of recursion needs to do , That is, the processing of data , Including the value returned by the next level of recursion and the current round of value processing ;③ This recursion needs to return the value of the upper recursion .

example

Try your best to explain the topic , The title is as follows :
 Insert picture description here
Recursion is always processed up from the end of recursion . So its code is :/**

  • Definition for singly-linked list.
  • struct ListNode {
  • int val;
    
  • ListNode *next;
    
  • ListNode(int x) : val(x), next(NULL) {}
    
  • };
    /
    // recursive
    class Solution {
    public:
    ListNode
    swapPairs(ListNode* head) {
    // Recursive termination condition
    if(headnullptr||head->nextnullptr)
    return head;
    // What this level recursion needs to do
    ListNode *node=swapPairs(head->next->next);
    ListNode *temp=head->next;
    head->next=node;
    temp->next=head;
    // Return the value of upper level recursion
    return temp;
    }
    };
原网站

版权声明
本文为[You stole my name]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010515501647.html