关于递归函数的问题,急需大佬解答
本帖最后由 壳970527 于 2022-12-8 10:29 编辑#include <stdio.h>
struct cityLN {
char name;
int population;
struct cityLN *next;
};
void printCities(struct cityLN *ct);
struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt);
int main(){
struct cityLN c1 = {"Hiratsuka", 258, NULL},
c2 = {"Odawara", 190, NULL},
c3 = {"Yokosuka", 396, NULL},
c4 = {"Kamakura", 172, NULL},
c5 = {"Chigasaki", 242, NULL},
c6 = {"Fujisawa", 434, NULL};
struct cityLN *head = NULL;
head = &c1; c1.next = &c2;c2.next = &c3; c3.next = &c4; c4.next = &c5; c5.next = &c6;
printf("Original: \n");
printCities(head);
printf("reverse: \n");
head = reverseCitiesRecursive(head, NULL);
printCities(head);
return 0;
}
void printCities(struct cityLN *ct){
if (ct != NULL) {
printf("(%-10s: population = %3d)", ct->name, ct->population);
printf("%s", (ct->next != NULL) ? " ->\n" : "");
printCities(ct->next);
}
else
putchar('\n');
}
struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt){
}
最后一行的reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt)函数设计,他原来的顺序是c1->c2->c3->c4->c5->c6这样依次打印出来,而这个函数的作用是让他变成c6->c5->c4->c3->c2->c1
但是问题就出在于必须使用递归,他的输入值时head,head是c1,如果把c1->next更改为NULL,那么这个递归就无法继续下去。卡在这里想了好久都不知道怎么解。我也思考了很多比如先倒过来但是不知道怎么下手,下面的图片是完成后运行代码的输出内容,请问下这个函数应该如何设计。
只能设计函数,其他地方不能修改
下图为执行后的结果图
struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt){
if (dt == NULL) {
return ct;
}
struct cityLN * tmp=dt->next;
dt->next=ct;
return reverseCitiesRecursive(dt,tmp);
} 壳970527 发表于 2022-12-8 10:29
struct cityLN * reverseCitiesRecursive(struct cityLN *ct, struct cityLN *dt){
if (dt == NULL) { ...
head = reverseCitiesRecursive(head, NULL);
你这个函数不对吧,调用的时候dt 就是NULL, 你这个什么也没干就 return ct了 struct cityLN * reverseCitiesRecursive(struct cityLN * ct , struct cityLN * dt)
{
struct cityLN * next , * r ;
r = dt ;
if(ct) {
next = ct -> next ;
ct -> next = dt ;
r = reverseCitiesRecursive(next , ct) ;
}
return r ;
}
页:
[1]