我有一个 C 语言练习要做,需要一些帮助。我必须编写一个递归函数( checkModOfPrevSum()
),它将检查存储的数字列表,如果每个 node%sum_of_previous_nodes == 0
的值.
对于每个节点,它必须打印该节点的值、先前节点的总和以及"is"或“否”,具体取决于 if node_value%sum_of_previous_nodes == 0
。打印必须以相反的顺序进行。
我必须使用的功能是这样的:
void checkModOfPrevSum(struct list *node, int sum) {.........}
不允许使用任何 while 或 for 循环。
例如,如果列表如下:(值为 5 的节点是头)
5 2 3 6 1 7 4
结果必须是:
4 [24] (YES) - 7 [17] (NO) - 1 [16] (YES) - 6 [10] (NO) - 3 [7] (NO) - 2 [5] (NO) - 5 [0] (YES)
如何编写代码?
最佳答案
我们初学者应该互相帮助。
对于我和你这样的初学者来说,这项作业并不容易完成。:)
给你。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert( struct node **head, const int a[], size_t n )
{
if ( *head != NULL ) head = &( *head )->next;
for ( size_t i = 0; i < n; i++ )
{
struct node *tmp = malloc( sizeof( struct node ) );
tmp->data = a[i];
tmp->next = *head;
*head = tmp;
head = &( *head )->next;
}
}
void checkModOfPrevSum( struct node *head, long long int sum)
{
if ( head != NULL )
{
if ( head->next != NULL )
{
checkModOfPrevSum( head->next, sum + head->data );
printf( " - " );
}
printf( "%d [%lld] (%s)", head->data, sum, sum % head->data == 0 ? "YES" : "NO" );
}
}
int main( void )
{
struct node *head = NULL;
int a[] = { 5, 2, 3, 6, 1, 7, 4 };
const size_t N = sizeof( a ) / sizeof( *a );
insert( &head, a, N );
checkModOfPrevSum( head, 0 );
return 0;
}
程序输出为
4 [24] (YES) - 7 [17] (NO) - 1 [16] (YES) - 6 [10] (NO) - 3 [7] (NO) - 2 [5] (NO) - 5 [0] (YES)
当然,列表实现并不完整。您可以根据需要进一步开发它。
关于c - 空函数C递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596191/