我正在寻找一段时间的考试答案。该问题要求递归函数搜索链表并返回指向可被3整除的数据的节点的指针,如果没有任何东西可以被3整除,则返回NULL。
答案是:
struct node {
int data;
struct node *next;
};
struct node * divThree(struct node * head) {
if (head == NULL)
return NULL;
if (head->data % 3 == 0)
return head;
return divThree(head->next);
}
如果头节点或下一个节点都不能被3整除,该函数如何继续跟踪链表?我只看到它检查头部和头部指向的数据。
答案 0 :(得分:2)
当你执行以下操作时,这是一个递归函数:
return(head->next);
它检查next
节点,并在该next
节点上重复整个函数,当它不符合条件时,它会检查next
,是head->next->next
,如果不是,则会检查next
,直到列表末尾或找到结果。
答案 1 :(得分:1)
divThree(x)
会致电divThree(x->next)
,divThree(x->next->next)
会调用divThree(x->next->next->next)
来调用divThree
,依此类推,直到使用参数{{1}调用z
这样z == NULL
或z->data % 3 == 0
。