首页 > 解决方案 > c++中的多重递归

问题描述

我理解简单的递归,但我很难理解多重递归。有人可以说明此代码多次递归的执行顺序吗?

#include <iostream>
using namespace std;
struct node{
  int data;
  node * next;
  node();
  node(node* &o):data(o->data){};
  node(int a):data(a),next(NULL){};
};
void initialize(node *& head){
  head = new node(0);
  node *temp(head);
  for(int i = 1; i < 10; i++){
    temp->next = new node(i);
    temp = temp->next;
  }
}
void function(node* head, int index){
  if(index >= 3){
    cout << "you hit the base case" << endl;
    return;
  }
  else if(index < 3){
     cout << "Before first call" << endl; 
     function(head->next, index+1);                     //call one
     cout << "After he first call" << endl;
     function(head->next, index+1);                     //call two
     cout << "After the second call" << endl;
  }
}
int main() {
  node * head = nullptr;
  int index = 1;
  initialize(head);
  function(head, index);
} 

先感谢您 :)

标签: c++recursion

解决方案


推荐阅读