实现将在递归调用之后通过返回到达该行。如果一个人不熟悉递归,可能需要一些时间来适应它。如果您能够使用调试器,我强烈建议您尝试使用它并检查调用堆栈和局部变量值。但是,递归调用的序列可以扩展如下,使用您的示例,使用伪编码符号,其中插入值。
1. call lindex({1,2,3,4}, 0, 2):
int size=strlen(in); // assigns 4
if(0 == 4){ // condition is false
}
int ans = lastIndex({1,2,3,4}, 1, 2); // assigns 3, as we see below
if(3 != -1){ // condition is true
return 3;
}
2. call lindex({1,2,3,4}, 1, 2):
int size=strlen(in); // assigns 4
if(1 == 4){ // condition is false
}
int ans = lastIndex({1,2,3,4}, 2, 2); // assigns 3, as we see below
if(3 != -1){ // condition is true
return 3;
}
3. call lindex({1,2,3,4}, 2, 2):
int size=strlen(in); // assigns 4
if(2 == 4){ // condition is false
}
int ans = lastIndex({1,2,3,4}, 3, 2); // assigns 3, as we see below
if(3 != -1){ // condition is true
return 3;
}
4. call lindex({1,2,3,4}, 3, 2):
int size=strlen(in); // assigns 4
if(3 == 4){ // condition is false
}
int ans = lastIndex({1,2,3,4}, 4, 2); // assigns -1, as we see below
if(-1 != -1){ // condition is false
}else{
if(in[3] == 2){ // condition is true
return 3;
}
5. call lindex({1,2,3,4}, 4, 2):
int size=strlen(in); // assigns 4
if(4 == 4){ // condition is true
return -1;
}
如果我们讨论各个步骤的语义,实现会变得更容易理解。首先,检查起始索引点是否在数组后面,在这种情况下,找不到所需的数字并返回 -1。否则,我们在数组的尾部寻找要找到的数字。如果可以在那里找到,我们返回在递归调用中找到的索引。否则,我们测试当前位置是否与要查找的所需数字相等,因为它不会出现在数组的尾部。总的来说,这会返回搜索到的数字最右边出现的索引(如果它被包含的话)。
从递归调用返回的“后退”是通过调用堆栈完成的;每个递归调用都有自己的一组局部变量。